Implementing behaviors

Behaviors were introduced in Silverlight 3 and provide a new way of adding interactivity to UI elements without the use of code. Behaviors are reusable pieces of code that extend either a specific UI element (for example, TextBox) or a whole type of elements (for example, FrameworkElement). Behaviors are basically self-contained pieces of functionality that go along with the object they are attached to and react to its environment. Behaviors contain two important elements—Trigger and Action. Trigger elements are used to invoke an action. Take, for example the PlaySoundAction behavior that comes bundled with Expression Blend 4. When adding this behavior, you need to set a trigger (when will the sound be played) such as MouseLeftButtonDown or Loaded, and then set the action itself, which is what sounds to play when the trigger triggers.

One important role of behaviors is controlling storyboard animations. Let's see how we can control animations without the use of code behind!

Triggering storyboards by using behaviors

Adding behaviors using Blend 4 is as simple as it gets. Open a new Silverlight 4 project in Visual Studio 2010, and name it Chapter3-Behaviors. Add the following code snippet to your MainPage.xaml file:

<Rectangle x:Name="rectangle" Margin="32,79,183,92" Stroke="Black" RenderTransformOrigin="0.5,0.5">
<Rectangle.Fill>
<LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
<GradientStop Color="Red" Offset="0"/>
<GradientStop Color="#FFFF841C" Offset="1"/>
</LinearGradientBrush>
</Rectangle.Fill>
</Rectangle>
<Button Content="Play" HorizontalAlignment="Left" Height="32" Margin="32,0,0,35" VerticalAlignment="Bottom" Width="90">
</Button>

Directly under the UserControl element, add the following storyboard:

<UserControl.Resources>
<Storyboard x:Name="Storyboard1">
<DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.RenderTransform). (CompositeTransform.TranslateX)" Storyboard.TargetName="rectangle">
<EasingDoubleKeyFrame KeyTime="0" Value="0"/>
<EasingDoubleKeyFrame KeyTime="0:0:0.6" Value="160"/>
</DoubleAnimationUsingKeyFrames>
</Storyboard>
</UserControl.Resources>

The storyboard uses keyframes-based animation to move the rectangle to the right-hand side using translations.

Once done, right-click on MainPage.xaml and choose Open in Expression Blend....

The file will now open in Expression Blend 4. While there is a lot to talk about Expression Blend, this book isn't dedicated to the subject and, thus, I highly recommend you to buy one of the many books that discuss it in detail.

In Expression Blend, mark the button we just created, and then click on Assets and choose Behaviors, as shown in the following screenshot:

Triggering storyboards by using behaviors

Drag the ControlStoryboardAction behavior from the board to the Play button.

On the right-hand side, you should notice the following menu:

Triggering storyboards by using behaviors

Here you can see the two parameters we discussed earlier—Trigger and Action. Under the Trigger section, you can select which event will trigger this behavior. In our example, we are going to leave it on Click as we want to react to the button's Click event. Under Common Properties, you can select what's going to happen and on which Storyboard element. Leave the Play action in place and under Storyboard, select Storyboard1.

Build and run your application, and press the play button. You've managed to trigger the animation using a behavior and not code behind.

But what if you want to have even more control and build your own behavior? Well, you surely can. Let's create a behavior that will stop and play the animation from the beginning every time you hover over the associated object.

Creating your own behavior

Before you create your own storyboard-related behavior, you must have something to control. Create a new Silverlight 4 project in Visual Studio 2010 and name it Chapter3-NewBehavior. In your project, create a new shape (like a rectangle) and add animation to it (by creating a storyboard and then using one of the animation types—ColorAnimation, DoubleAnimation, or PointAnimation). Once done, right-click on the Silverlight project, select Add and then Class. Name the class ReplayAnimationBehavior.

Add a reference in your project for System.Windows.Interactivity.dll.

In order to create a behavior, the first thing you should do with the class is tell it that it's going to be a behavior. Change your class declaration, so it will inherit from the Behavior<T> base class, where T stands for generic type. In our case, we are going to use FrameworkElement. Change your class declaration as follows:

public class ReplayAnimationBehavior : Behavior<FrameworkElement>

Each behavior consists of two main activities—OnAttached and OnDetached—which define what happens to the behavior once it's attached to an object and when it is detached, respectively. We want to react whenever the mouse hovers over the attached object, so in our attached property we are going to attach the MouseEnter event. Likewise, we are going to detach the event when the behavior is detached from the object.

Add the following methods to your behavior:

protected override void OnAttached()
{
base.OnAttached();
this.AssociatedObject.MouseEnter += new MouseEventHandler(AssociatedObject_MouseEnter);
}
protected override void OnDetaching()
{
base.OnDetaching();
this.AssociatedObject.MouseEnter -= AssociatedObject_MouseEnter;
}

Pay special attention to the object we are attaching the event to. Using AssociatedObject, you can get and set all of the properties of the object you are attaching the behavior to!

Now it's time to define the event handler. As this is a simple example, we are going to hardcode the name of the storyboard within the method. This shouldn't be done in a real production environment of course. Add the following event handler to your behavior:

void AssociatedObject_MouseEnter(object sender, MouseEventArgs e)
{
(this.AssociatedObject.FindName("Storyboard1") as Storyboard).Stop();
(this.AssociatedObject.FindName("Storyboard1") as Storyboard).Begin();
}

The method is quite simple:

  1. Find an element using the FindName method.
  2. Cast it as a Storyboard object.
  3. Then, stop and play the animation.

We now have a behavior! The last thing we need to do is attach it to an object.

Open MainPage.xaml and add the following namespaces, which represent the interactivity between DLL and our behavior:

xmlns:local="clr-namespace:Chapter3_NewBehavior"
xmlns:interactivity="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"

Build the application and attach the new behavior to your object using the following code snippet:

<interactivity:Interaction.Behaviors>
<local:ReplayAnimationBehavior/>
</interactivity:Interaction.Behaviors>

Build and run your application, and you should see your behavior in action every time you hover over the object.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
13.58.137.218