By John at November 02, 2009 15:57
Filed Under: Techy
I would encourage everyone who works with Silverlight to take a good hard look at Behaviors. A Behavior is basically some code-behind logic that operates on Silverlight UI elements, bundled into a nice little package that can be in Xaml. Behaviors can support parameters as well, making them both flexible and extensible. In Expression Blend 3, several behaviors are provided out-of-the-box. There is a drag/drop behavior, and a behavior that allows you to control storyboard animations based on events, just to name a couple.
Below is a Silverlight example of a Rectangle that uses these two behaviors. When the mouse enters the rectangle, it will alternate colors between red and yellow. You can also drag the rectangle around. Check it out…
And here is the Xaml representation of the above Silverlight application:
- <UserControl
- xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
- xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
- xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
- xmlns:im="clr-namespace:Microsoft.Expression.Interactivity.Media;assembly=Microsoft.Expression.Interactions"
- xmlns:il="clr-namespace:Microsoft.Expression.Interactivity.Layout;assembly=Microsoft.Expression.Interactions"
- x:Class="BehaviorsDemo.MainPage"
- Width="640" Height="480">
- <UserControl.Resources>
- <Storyboard x:Name="BlueToYellow" AutoReverse="True" RepeatBehavior="Forever">
- <ColorAnimationUsingKeyFrames BeginTime="00:00:00" Storyboard.TargetName="rectDemo" Storyboard.TargetProperty="(Shape.Fill).(SolidColorBrush.Color)">
- <EasingColorKeyFrame KeyTime="00:00:01" Value="#FFFEFF00"/>
- </ColorAnimationUsingKeyFrames>
- </Storyboard>
- </UserControl.Resources>
- <Canvas x:Name="LayoutRoot" Background="White">
- <Rectangle x:Name="rectDemo" Fill="#FF000BFF" Height="51" Width="58" Canvas.Left="202" Canvas.Top="116">
- <i:Interaction.Triggers>
- <i:EventTrigger EventName="MouseEnter">
- <im:ControlStoryboardAction Storyboard="{StaticResource BlueToYellow}"/>
- </i:EventTrigger>
- <i:EventTrigger EventName="MouseLeave">
- <im:ControlStoryboardAction Storyboard="{StaticResource BlueToYellow}" ControlStoryboardOption="Stop"/>
- </i:EventTrigger>
- </i:Interaction.Triggers>
- <i:Interaction.Behaviors>
- <il:MouseDragElementBehavior />
- </i:Interaction.Behaviors>
- </Rectangle>
- </Canvas>
- </UserControl>
As you can see this is about 30 lines of Xaml that I was able to produce with simple point and click in Expression Blend. Notice the elements that start with <i:…/> These are the behaviors that control the storyboard and mouse drag.
The beauty of Behaviors is that they are so easy to use and are highly reusable. They can also be quite powerful when combined together to create complex user interactions.