Animated Panel layout transitions in WPF and Silverlight using Blend Behaviors
I wrote a blog article a few weeks ago about how to write animated panels. Another way of doing this was introduced to me by Stuart Richardson using Blend Behaviors which I like a lot. It’s fairly simple so this is going to be a short post. Suppose you have a panel, say a StackPanel that knows nothing about animating layout changes:
<StackPanel x:Name="stack" MouseLeftButtonUp="stack_MouseLeftButtonUp">
<Rectangle Fill="Red" Width="100" Height="100"/>
<Rectangle Fill="Green" Width="100" Height="100"/>
<Rectangle Fill="Blue" Width="100" Height="100"/>
</StackPanel>
private void stack_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
stack.Orientation = stack.Orientation == Orientation.Horizontal ?
Orientation.Vertical : Orientation.Horizontal;
}
When we click on the rectangles, the panel switches orientation – snap, the items appear instantly at their new location.
Now in Blend, we can just add a behavior, a FluidMoveBehavior:
And this causes the state transitions to animate. You can even edit the Ease’s in Blend:
To see what has happened in the XAML, here is a listing:
<StackPanel x:Name="stack" MouseLeftButtonUp="stack_MouseLeftButtonUp">
<i:Interaction.Behaviors>
<ei:FluidMoveBehavior AppliesTo="Children"/>
</i:Interaction.Behaviors>
<Rectangle Fill="Red" Width="100" Height="100"/>
<Rectangle Fill="Green" Width="100" Height="100"/>
<Rectangle Fill="Blue" Width="100" Height="100"/>
</StackPanel>
This is a really simple way of doing animated panels in WPF and Silverlight.
Whilst we are on the topic of Blend behaviors, take a look at the MouseDragElementBehavior:
<StackPanel x:Name="stack" MouseLeftButtonUp="stack_MouseLeftButtonUp">
<i:Interaction.Behaviors>
<ei:FluidMoveBehavior AppliesTo="Children"/>
</i:Interaction.Behaviors>
<Rectangle Fill="Red" Width="100" Height="100">
<i:Interaction.Behaviors>
<ei:MouseDragElementBehavior/>
</i:Interaction.Behaviors>
</Rectangle>
<Rectangle Fill="Green" Width="100" Height="100">
<i:Interaction.Behaviors>
<ei:MouseDragElementBehavior/>
</i:Interaction.Behaviors>
</Rectangle>
<Rectangle Fill="Blue" Width="100" Height="100">
<i:Interaction.Behaviors>
<ei:MouseDragElementBehavior/>
</i:Interaction.Behaviors>
</Rectangle>
</StackPanel>
Adding this to the elements allows them to be dragged around with the mouse. If you want to customise the drag drop, there are DragBegun, Dragging and DragFinished events that you can handle to do your custom things.
This is pretty cool stuff!
Written by Paul Tallett
Comments
- Anonymous
April 07, 2011
Really usefull, thanks ! How about custom behaviours ? Any of them are usefull ? Does it make sense to write one ?