Tuesday, March 01, 2011

Silverlight Behaviors, Triggers and Actions

My recent new love when doing Silverlight Development is Expression Blend’s Interactivity API that gives you some really neat support for attaching behaviors, triggers and actions to your elements, which in turn lets you structure your code better and allows you to reuse it more often (It boggles my mind why these are not part of core Silverlight).
You can download the Expression Blend SDK for free here, but you also get it with Expression Blend 3.0.
How often haven’t you done something like this:

<Button OnClick=”ShowToolsWindow” Content=”Show Tools” />

and in the code behind:

private void ShowToolsWindow(object sender, RoutedEventArgs e)
{
           ToolsWindow.Visibility = Visibility.Visible;
}

While this probably isn’t much code, imagine a whole toolbar or menu each with code in two places, and especially the code-behind more or less the exact same, but with a different target. And if I remove a button, I also have to remember to remove the eventhandler. Enter triggers and actions…
With the Expression SDK we can create a trigger that does this for us.

public class ToggleVisibilityAction : TargetedTriggerAction<UIElement>
{

protected override void Invoke(object parameter)
{
this.Target.Visibility = this.Target.Visibility == Visibility.Visible ? Visibility.Collapsed : Visibility.Visible;
}
}

Read more: Kan on Silverlight