Theming in Silverlight

A good design is appreciated if the look and feel is consistent across the application or site you develop. The first and the most best,popular option that comes to our minds is "Themes".

Silverlight allows developers to create rich styles for controls.
Every style has a unique key to identify and it is targeted for a particular element.
To apply style to an element,you have to bind it’s Style property with the unique key of the style defined in the resources at application or local level or defined in resource dictionary.

But is it possible to avoid inline (StaticResource) binding of styles and implicitly apply them to all elements going by the concept of "Themes".
The answer is "YES" and here is the solution. 

How to go about.  ?
In addition to Silverlight library, you will have to install the Silverlight toolkit.
The latest release is here.
There are inbuild themes already available in Silverlight toolkit,but I will create a simple theme from scratch.

Here are the steps:
1) Open Visual Studio and select a Silverlight application.

Silverlight application
2) Add a new folder "Themes" to the project.
Add three Silverlight resource dictionaries each for red,blue and green theme. Set the "Build Action" to Content for each xaml resource file in properties panel ,so that they are added to .xap file and they can be relatively located.

Silverlight resource dictionary       Project structure

Setting the build action to content

 

3) Add reference to "System.Windows.Controls.Theming".
Adding System.Windows.Controls.Theming to the project

4) In MainPage.xaml, I have added a ListBox with names of colors as ListBoxItems.
In a Stackpanel elements like Button,TextBlock and RadioButton have been added.
What I wish to do is on selecting a particular color from ListBox, I want the themes to be applied to all the elements in the StackPanel without StaticResource binding. But first let us create styles for a every element for red,green and blue themes respectively.

Elements in MainPage.xaml file

Code in MainPage.xaml file.

<UserControl x:Class="Themes_Application.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d" d:DesignWidth="640" d:DesignHeight="480">
  <Grid x:Name="LayoutRoot"  HorizontalAlignment="Center">
        <Grid.RowDefinitions>
            <RowDefinition Height="100"/>
            <RowDefinition/>
        </Grid.RowDefinitions>
        <ListBox x:Name="lstThemeColor" SelectionChanged="lstThemeColor_SelectionChanged" Width="Auto" BorderBrush="Black" BorderThickness="1" Height="Auto" Grid.Row="0">
            <ListBoxItem Content="Red"/>
            <ListBoxItem Content="Blue"/>
            <ListBoxItem Content="Green"/>
        </ListBox>

        <StackPanel Grid.Row="1" Orientation="Horizontal" x:Name="pnlElements" >
            <Button Height="50" Width="100" Content="Button1" Margin="5"/>
            <Button Height="50" Width="100" Content="Button2" Margin="5"/>
            <Button Height="50" Width="100" Content="Button3" Margin="5"/>
            <TextBlock Text="TextBlock1" Width="Auto" Height="30" Margin="5"/>
            <TextBlock Text="TextBlock2" Width="Auto" Height="30" Margin="5" />
            <RadioButton Content="RadioButton1" Width="Auto" Height="30" Margin="5"/>
            <RadioButton Content="RadioButton2" Width="Auto" Height="30" Margin="5"/>
        </StackPanel>

    </Grid>
</UserControl>

5) The best way to create styles is to copy the xaml code created in Expression Blend after right clicking the element and selecting the "Edit Template" option. Expression Blend provides excellent options to create styles. Change the color properties and edit the states for a particular control. Click here “http://www.silverlight.net/learn/tutorials/stylestemplatesvsm-cs/” to learn how to create styles,templates.
After copy-pasting styles for different colors in resource dictionary, remove the "x:Key" property from every style created  for a particular control as it is not required. Your “RedTheme.xaml ” will look like this. Similary there will be styles created for every type of element in BlueTheme.xaml and GreenTheme.xaml files.

Code in RedTheme.xaml file

6) Once the styles are in place ,we now write the logic to apply it to the elements in the StackPanel. The code is written in MainPage.xaml.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;

//this reference is required…
using System.Windows.Controls.Theming;

namespace Themes_Application
{
    public partial class MainPage : UserControl
    {
        Uri uri_resource;
        public MainPage()
        {
            InitializeComponent();
        }

        //on selecting a color value the theme should be applied.
        private void lstThemeColor_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            string color_name = ((ListBoxItem)(lstThemeColor.SelectedItem)).Content.ToString();
            if (color_name == "Red")
            {
                uri_resource = new Uri("Themes/RedTheme.xaml", UriKind.Relative);
            }
            else if (color_name == "Blue")
            {
                uri_resource = new Uri("Themes/BlueTheme.xaml", UriKind.Relative);
            }
            else if (color_name == "Green")
            {
                uri_resource = new Uri("Themes/GreenTheme.xaml", UriKind.Relative);
            }

            //get the theme file and apply it to elements in panel.
            ImplicitStyleManager.SetResourceDictionaryUri(pnlElements, uri_resource);
            ImplicitStyleManager.SetApplyMode(pnlElements, ImplicitStylesApplyMode.Auto);
            ImplicitStyleManager.Apply(pnlElements);
        }
    }
}

Here the ImplicitStyleManager is a class that provides methods to do the following tasks.

a) To first locate the resource dictionary which will apply styles to elements. Here it is the xaml files stored in “Themes” folder
b) To get the name of the parent element in which the child controls or descendants have to be applied styles.
c) To implicitly apply styles to the parent element and its descendants.

Thus without doing any StaticResource binding to any of the elements you can create Themes and apply them implicitly.
Here is the final output in browser.

      Green theme applied

       BlueTheme applied

Red Theme applied

Advertisements

How to consume/connect/use WCF service for Silverlight4 application.

The process is simple. You should know two things,what has to be provided as service.
Where it would be consumed.
Here Windows Communication Foundation lets you create services.
Silverlight application is the client which will consume it.

Steps for creating WCF service:
1) Select a Silverlight application hosted in Web application project.
2) Add to it a WCF service.

Img1
3) Three files will be added to your project.I have chosen the default names.

img2
4) The IService1.cs interface will define the contract and Service1.svc.cs will implement it.

Here MyHello is a simple method to return a message on input of a string.

Code in IService1.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;

namespace Sample1.Web
{
    [ServiceContract]
    public interface IService1
    {
        [OperationContract]
        string MyHello(string name);
    }
}

Code in Service1.svc.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;

namespace Sample1.Web
{
    public class Service1 : IService1
    {
        public string MyHello(string name)
        {
            return "Hello "+name+" from WCF service";
        }
    }
}

 
5) Once the service is created build the project and the view the .svc file in browser.

img3

 

Steps for consuming the service.
6) In our Silverlight application,in our xaml page we will add a textbox to enter a name , a button to call WCF service and a textblock to display the output.

img6  

<UserControl x:Class="Sample1.MainPage" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    d:DesignHeight="300" d:DesignWidth="400">

    <Grid x:Name="LayoutRoot" Background="White">
        <Button Content="Click to call WCF Service" Height="52" HorizontalAlignment="Left"   Margin="44,148,0,0" Name="btn_CallService" VerticalAlignment="Top" Width="320" Click="btn_CallService_Click" />
        <TextBox Height="64" HorizontalAlignment="Left" Margin="44,60,0,0" Name="txt_EnterName" VerticalAlignment="Top" Width="319" />
        <TextBlock Height="52" HorizontalAlignment="Left" Margin="44,222,0,0" Name="txt_DisplayHello" Text="" VerticalAlignment="Top" Width="318" />
    </Grid>
</UserControl>

 
7) Your silverlight application  has to first discover the service created. So add a service reference to your silverlight application project.

 img4

The project structure.

img5
8) Finally the last step. Create a proxy which is an object of ServiceClient to access the method. The methods are loaded asynchronously hence you may not see the name of the method,but two additional methods,one to load method asynchronously and the other to do something once its completed.

 

Code in MainPage.xaml.cs

using System;
using System.Windows;
using System.Windows.Controls;
using System.ServiceModel;

namespace Sample1
{
    public partial class MainPage : UserControl
    {
        public MainPage()
        {
            InitializeComponent();
        }

        private void btn_CallService_Click(object sender, RoutedEventArgs e)
        {
            ServiceReference1.Service1Client proxy = new ServiceReference1.Service1Client();

           //Hooking up the event to display the entered text.
            proxy.MyHelloCompleted +=new EventHandler<ServiceReference1.MyHelloCompletedEventArgs>    (proxy_MyHelloCompleted);

           //Passing the text input
            proxy.MyHelloAsync(txt_EnterName.Text);

        }

     

        void proxy_MyHelloCompleted(object sender, ServiceReference1.MyHelloCompletedEventArgs e)
        {
            txt_DisplayHello.Text = e.Result;
        }

    }
}

9) Its done. Now when you run your application,on click event of button the WCF service will call the function asynchronously to take in the entered text and display the output in textblock.

img7

 

Note: In Silverlight 4 application when using a WCF service I did not have to change the bindings from wsHttpBinding to basicHttpBinding.

Else we had to do it in  earlier versions of Silverlight applications.

Managed Extensibility Framework in Silverlight4

Managed Extensibility Framework(MEF) is an old concept of building extensible applications. But it was not a part of Silverlight3. To work on MEF we had to get the MEFPreview8(latest version) from Codeplex and then include the .dll files in our project,to implement it.
Silverlight 4 has got it inbuilt. This is great.So let us first understand to see what MEF is.

Managed Extensibility Framework revolves around three concepts.
Export:   What you need to provide.
Import:   Get what has been provided.
Compose: Do something with what you got.

Lets c it practically 🙂
I created a Silverlight application named MEF hosted in ASP.Net Web Application project .
Then I included another Silverlight Usercontrol . Named it as LocalControl.xaml.
Img1
To implement MEF,we  have to add reference to :
System.ComponentModel.Composition.dll  and System.ComponentModel.Composition.Initialization.dll

img2 img3

The logic goes this way:
I have to export usercontrol that I created in LocalControl.xaml file and import it in my MainPage.xaml.
Code added to LocalControl.xaml file:

<UserControl x:Class=”MEF.LocalControl”
    xmlns=”http://schemas.microsoft.com/winfx/2006/xaml/presentation”
    xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml”
    xmlns:d=”http://schemas.microsoft.com/expression/blend/2008″
    xmlns:mc=”http://schemas.openxmlformats.org/markup-compatibility/2006″
    mc:Ignorable=”d”
    Height=”200″ Width=”200″>
    <StackPanel Background=”Red”>
        <RichTextArea Width=”180″ Background=”Beige” Height=”180″ Margin=”10″ ></RichTextArea>
    </StackPanel>
</UserControl>

Code Behind in LocalControl.xaml.cs file.

using System.ComponentModel.Composition;namespace MEF
{
   [Export(typeof(UserControl))]   
    public partial class LocalControl : UserControl
    {
        public LocalControl()
        {
            InitializeComponent();
        }   

}
}

The Export attribute tells MEF that the LocalControl is available for service.

In MainPage.xaml to display this Control in Stackpanel on click event of button MEF concept has been used.
Code added to MainPage.xaml

<UserControl x:Class=”MEF.MainPage”
    xmlns=”http://schemas.microsoft.com/winfx/2006/xaml/presentation”
    xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml”
    xmlns:d=”http://schemas.microsoft.com/expression/blend/2008″
    xmlns:mc=”http://schemas.openxmlformats.org/markup-compatibility/2006″
    mc:Ignorable=”d”
    d:DesignHeight=”300″ d:DesignWidth=”400″
    xmlns:controls=”clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls”>    <Grid x:Name=”LayoutRoot” Background=”White”>
        <StackPanel Margin=”10″>
            <StackPanel Width=”250″ Height=”250″ x:Name=”pnl_Display” Background=”Brown”></StackPanel>
            <Button x:Name=”btn_DisplayControl” Height=”30″ Width=”200″  Content=”Click to display control”     Click=”btn_DisplayControl_Click”/>
        </StackPanel>    </Grid>
</UserControl>
 

Code behind in MainPage.xaml.cs

using System.ComponentModel.Composition;
namespace MEF
{
    public partial class MainPage : UserControl
    {
        [Import]
        public UserControl myControl =  new UserControl();      

        public MainPage()
        {
            InitializeComponent();   

           PartInitializer.SatisfyImports(this);
        }  

       private void btn_DisplayControl_Click(object sender, RoutedEventArgs e)
        {
             pnl_Display.Children.Add(myControl);
        }
    }
}

If  you observe the code in MainPage.xaml.cs while creating an object I have simply created a usercontrol object.  It is nowhere specified that it is of type LocalControl. Still after I run my project I am able to see the LocalControl on click event of button.

So this is MEF’s magic.

The Import attribute gets whatever has been exported . We are right now exporting only one usercontrol.
If there are many exports, you have to use ImportMany attribute.

Once the imports are done,you have to tell our MainPage usercontrol to accept the imports.
 PartInitializer.SatisfyImports(this) will do the job.
If this statement is not added you won’t see the LocalControl in StackPanel on click event of button.

Here are the snapshots:

img4 
  StackPanel with RichtexArea   control in LocalControl.xaml file
img5
StackPanel where the LocalControl has to be displayed on clicked event of button in MainPage.xaml
img6

This application is very very basic . But the power of MEF is much more. 

I would be blogging more on this.. 🙂

The best links to get started :

http://silverlight.net/learn/videos/all/using-mef-silverlight-4-extensibility/
http://blogs.msdn.com/gblock/archive/2009/11/30/building-the-hello-mef-dashboard-in-silverlight-4-part-i.aspx 

Controls in Silverlight(….Items Control)

An items control is used to customize list controls.

If you are creating an items control from scratch follow these steps.
I am declaring a class Person with two properties name and city in my project.
My main aim is to bind the objects of Person class to an items control and set their
appearance.

Project files Person  Class
Project Files

public class Person
    {
        private string pname;
        public string PName
        {
            set{ pname = value; }
            get{ return pname; }
        }
        private string city;
        public string PCity
        {
            set{ city = value; }
            get{ return city; }
        }
        public Person()
        {
        }
    }

An Itemscontrol includes four important elements.

  • Items
  • ItemsTemplate
  • Template
  • ItemsPresenter

Step1: Adding items to control
Add reference to your namespace. Create objects of Person class and add it to the Items property.

Step2: Setting the appearance of individual item.
Set the template for individual item. Here you have to set the DataTemplate property within ItemTemplate and bind the elements to the properties of objects created. If you do not bind you will get the data in Namespace.Class format.

Step3: Setting the template of control.
This step is optional. Setting the template means you are recreating the control.
You are adding and removing the parts of a control.Once the elements are added to set the appearance , do add a very important element called the ItemsPresenter.

ItemsPresenter like ContentPresenter in content controls makes your items visible .Your items won’t be visible if you set the template and forget to  add ItemsPresenter.

You can even decide the layout of items in the panel by setting the ItemsPanelTemplate.It is again optional.

Here is the whole xaml code following the above steps with a pic below of my custom Itemscontrol.

CustomItemsControls

<UserControl
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:Controls_ItemsControl"
    x:Class="Controls_ItemsControl.MainPage"
    Width="640" Height="480">
<Grid x:Name="LayoutRoot" Background="White">
<ItemsControl Height="205" Width="300" VerticalAlignment="Top" Margin="170,23,170,0">
    <!– Adding the items to the control–>
        <ItemsControl.Items>
            <local:Person PName="John" PCity="Banglore"></local:Person>
            <local:Person PName="Sammy" PCity="Bombay"></local:Person>
        </ItemsControl.Items>
    <!–Displaying and Setting the appearance of individual items–>
        <ItemsControl.ItemTemplate>
            <DataTemplate>
                <Grid>
                    <Grid.RowDefinitions>
                        <RowDefinition/>
                    </Grid.RowDefinitions>
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition/>
                        <ColumnDefinition/>
                    </Grid.ColumnDefinitions>
                    <Border Grid.Column="0" BorderBrush="CadetBlue"  BorderThickness="10">
                            <TextBlock  Text="{Binding PName}"></TextBlock>
                    </Border>
                    <Border Grid.Column="1" BorderBrush="DarkOrange"  BorderThickness="10">
                            <TextBlock  Text="{Binding PCity}"></TextBlock>
                    </Border>
                </Grid>
            </DataTemplate>  
        </ItemsControl.ItemTemplate>   
    <!–Setting the template of control–>   
    <ItemsControl.Template>
        <ControlTemplate>
            <Border BorderBrush="ForestGreen"  BorderThickness="10">
                <ItemsPresenter/>
            </Border>
        </ControlTemplate>
    </ItemsControl.Template>
</ItemsControl>
</Grid>
</UserControl>

Controls in Silverlight(Content Controls ..Part2)

In my previous post I wrote how to build simple content controls.

Controls even have states like: Normal,Pressed, MouseOver, Focussed, Disabled etc.

After applying a template to a control,if states have to be retained,then it is important to understand the VisualStateManager class.

Visual State Manager
VisualStateManager gives a standard protocol to define your states and transitions.
You can group your states and give individual behaviour to these states.
Let us look now how to customize a button. Once you set the template of a button,the button loses its states. To get back those states you have to use VisualStateManager and set the behaviors for the states.

Here I have defined two states "Normal" and "MouseOver" for a button.
The button is shaped as ellipse and on mouse over there is a change in its color.

Normal State     MouseOverState

Here is the code to customize the button.

<Button Grid.Row="2">
<Button.Template>
    <ControlTemplate>
    <Grid>
    <VisualStateManager.VisualStateGroups>
            <VisualStateGroup x:Name="CommonStates">
            <VisualState x:Name="Normal">
            <Storyboard>
                <ColorAnimation Storyboard.TargetName="btnColorBrush" Storyboard.TargetProperty="Color"
                To="Chocolate" Duration="0:0:0"></ColorAnimation>
            </Storyboard>
            </VisualState>
            <VisualState x:Name="MouseOver">
            <Storyboard>
            <ColorAnimation Storyboard.TargetName="btnColorBrush" Storyboard.TargetProperty="Color"
                To="DarkMagenta" Duration="0:0:0"></ColorAnimation>   
                </Storyboard>
            </VisualState>
            </VisualStateGroup>
        </VisualStateManager.VisualStateGroups>
    <Ellipse Width="100" Height="100">
        <Ellipse.Fill>
            <SolidColorBrush Color="Aqua" x:Name="btnColorBrush"></SolidColorBrush>
        </Ellipse.Fill>
    </Ellipse>
    <ContentPresenter Content="Hello" HorizontalAlignment="Center"
     VerticalAlignment="Center"/>
        </Grid>

    </ControlTemplate>
</Button.Template>
</Button>

 

Controls in Silverlight.(Part1… Content Controls)

Silverlight provides  a standard set of controls to let you build your application user interface.

The standard controls include:
CheckBox,RadioButton,Button,ScrollViewer,TextBox,ProgressBar,HyperlinkButton,ListBox,
PasswordBox,ComboBox,Slider..etc..

Built-in Controls in Silverlight

Additional controls are available at http://www.codeplex.com/Silverlight.

Most of times we want to customize the appearance of a control . In this post we shall see how
to customize a Silverlight control and make your own custom control. Follow these simple steps to get started.

  • Determine whether your control is a ContentControl or ItemsControl by looking at the control base class.
  • ContentControl : It has two important properties Content and Template. The Content property specifies the unique content for each instance of the control. The Template property defines a common appearance to all the instances of the controls.
  • ItemsControl : This control is used to customize the appearance of the list controls where the content is more than one item.The Content and Template properties are extended to set the content and appearance of each item.

Case 1) Working with Content Controls

To create a simple content control,you have to set the Template property which defines the appearance .
To add the control’s content into the template ,you need another container called ContentPresenter.Else your content will not be visible in the template.

The code below creates two content controls , the first one is a simple content control,with no elements.
The second content control includes a textbox as it’s content.So the template defined now applies to textbox and you get a  customized textbox.

ContentControl1

Here is the code.

<Grid x:Name=”LayoutRoot” Background=”White” Width=”400″ Height=”380″>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<!–Creating simple content control–>
<ContentControl Grid.Row=”0″ x:Name=”cstControl1″>
<ContentControl.Template>
<ControlTemplate>
<Border BorderBrush=”Chocolate” BorderThickness=”30″
CornerRadius=”10″ >
<ContentPresenter Content=”Hello”/>
</Border>
</ControlTemplate>
</ContentControl.Template>
</ContentControl>

<!–Customizing the appearance of textbox–>
<ContentControl Grid.Row=”1″ x:Name=”cstTextControl1″ Width=”300″ Height=”100″>
<ContentControl.Content>
<TextBox Text=”Custom TextBox” Foreground=”DarkMagenta” />
</ContentControl.Content>
<ContentControl.Template>
<ControlTemplate>
<Border BorderThickness=”20″ CornerRadius=”10″ >
<Border.BorderBrush>
<LinearGradientBrush >
<GradientStop Color=”BlueViolet” Offset=”0″></GradientStop>
<GradientStop Color=”BlanchedAlmond” Offset=”1″></GradientStop>
</LinearGradientBrush>
</Border.BorderBrush>
<ContentPresenter/>
</Border>
</ControlTemplate>
</ContentControl.Template>
</ContentControl>
</Grid>

Behaviors and Actions in Blend3

Behaviors add interactivity to your application without having to write any code.
They are reusable pieces of packaged code that can be dragged onto any object to change its own or
other object’s properties,control storyboards ,change layout properties etc..
Behaviors  not necessarily be invoked by triggers,they work when some conditions are met.

An Action is an object that can do something..
A Trigger reacts to the cause and invokes one or more Actions.

Expression Blend 3 provides by default some behaviors and Actions in the asset panel…..

Behaviours and Actions in Asset Panel

Behaviours and Actions in Asset Panel

Here are some examples:

1) ControlStoryBoardAction: Lets u play,start,stop,pause a storyboard.
Here the storyboard animates the width property of a rectangle on click event of Button.
You have to drag the ControlStoryBoardAction on to your button and set the properties.

Setting properties for ControlStoryBoardAction

Setting properties for ControlStoryBoardAction

Storyboard

Storyboard

Code for animating the width of an ellipse on click of button

Code for animating the width of an ellipse on click of button

2) ChangePropertyAction: Changes the property and lets u animate it over some duration.
Here the opacity of the ellipse varies on click of the button.
Drag the action on button and set the properties.
There are options available to ease in and ease out your animation…over time.

Setting properties for ChangePropertyAction

Setting properties for ChangePropertyAction

Button nd ellipse

Code to change the opacity of ellipse on click of button

Code to change the opacity of ellipse on click of button

3) FluidMotionBehaviour: Animates the layout properties of objects in panel.
Here the button flies in from left in the canvas which is its parent container.
You can set the direction of easing in/out in x and y direction with options available in properties panel

Setting properties for FluidMotionbehaviour

Setting properties for FluidMotionbehaviour

Ease in/out options

Ease in/out options

pic11

Code for changing layout properties of button in canvas

Code for changing layout properties of button in canvas

4) MouseDragElementBehaviour:  It lets the object within the parent container to reposition.
Here the ellipse can be dragged within the boundaries of the button.

MouseDragElementBehaviour properties

MouseDragElementBehaviour properties

pic12

Code for moving ellipse in a button

Code for moving ellipse in a button

5) GotoStateAction: Changes to visual state
Here the rectangle and ellipse colliding animation is captured by a state.
This state is transitioned to on click event of a button.

Setting properties of GotoStateAction

Setting properties of GotoStateAction


pic13

Push state code including storyboard to animate

Push state code including storyboard to animate

Code for switching to push state..

Code for switching to push state..

You can also get more behaviors from the Expression Studio site.
Navigate to Expression Gallery to find more behaviors.