2009

Using Data Binding in the Carousel Control

Author: Steve Li
Posted on: 03 Dec 2009
This article shows how data binding can be used with the CarouselControl to create great UI.

Download: Source

Note: You will need to have Silverlight developer tools installed on your machine.
Visit Silverlight Official WebSite to learn more.

SvFx Carousel control supports data binding to simplify data display tasks. You can easily specify how data will be presented by defining custom item template. Data binding inside the carousel control can be used to present services or goods, list of employees or any other list of data.

ItemsControl provides flexible ways to work with data binding in Silverlight. Data binging is a connection between logic and UI. It means that you may build logic model in your application, populate it with custom data, then specify UI independently and finally connect data to the UI.

Let's consider the following scenario: We need to display information about employees of a company. To solve this task we'll use Cellbi SvFx Carousel control.

The following image shows how data will be presented:

Ellipse Carousel

Or the same data shown using vertical carousel layout:

Vertical Ellipse Carousel

I want to note that Cellbi SvFx Carousel control can specify not only UI. You will get total control of each item behaviour. Once defined, you can completelly change carousel control view without making any changes inside C# or VB code.

Lets take a look on how this can be done in more detail.

Logical Model.

As mentioned before we'll define our logical model as a list of employees. Each employee is characterised with a set of properties: FirstName, LastName, Department, HireDate. So the Employee class code will be the following:

public class Employee
{
  public string FirstName { get; set; }
  public string LastName { get; set; }
  public string Department { get; set; }
  public string BirthDate { get; set; }
  public string HireDate { get; set; }
  public string Photo { get; set; }
}

Using Employee class defined above we'll create sample data for this post. (Please take a look at the Data.cs file inside the source code)

Our data can be assigned to the UserControl.DataContext property. Carousel control should be declared inside the same UserControl.

The following code shows how DataContext property is assigned: (Note that GetData is a static method, which returns IEnumerable)

DataContext = Data.GetData();

Now let's create some UI to present our data.

UI Definition using Carousel Control

First of all let's add declaration of the Carousel control to the xaml file:

 <SvUx:CarouselControl 
x:Name="uxCarousel"
Width="800"
Height="500"
AlignCenter="True"
ZDepth="100"
VerticalAlignment="Stretch"
HorizontalAlignment="Stretch" >
<SvUx:CarouselControl.LocationSetup >
<SvFx:EllipseLocationSetup
Depth="40"
CanUseOpacity="False"
RadiusX="230"
RadiusY="110" />
</SvUx:CarouselControl.LocationSetup>
<SvUx:CarouselControl.Setup >
<SvFx:CycleTransitionSetup
SpeedRatio="2" />
</SvUx:CarouselControl.Setup>
</SvUx:CarouselControl>

Note that the code above will show empty carousel. Let's correct this.

Binding Carousel Control to Data

The following code shows how we can bind our data (assigned to the DataContext property):

Note that there is only one line of code added: ItemsSource="{Binding}". Now carousel control will be filled with data (from DataContext property).

Let's specify data template for each carousel item.

Data Template

The best way to let Carousel know how to display each item is to use ItemTemplate property. Item template will be used as visual template for each item of the carousel control.

CarouselItemTemplate is name of ItemTemplate which is placed inside application resources.

Data template specifies how UI will look like. You can use Expression Blend for visual design. The following code shows simple example:

 <DataTemplate 
x:Key="CarouselItemTemplate" >
<TextBlock
Text="{Binding FirstName}" />
</DataTemplate>

Note that we use binding expression here as well. In this case we access each item's property and obtain it's data.

The following code shows more complex example of data template:

 <DataTemplate 
x:Key="CarouselItemTemplate" >
<Grid >
<Grid.ColumnDefinitions >
<ColumnDefinition
Width="Auto" />
<ColumnDefinition
Width="Auto" />
</Grid.ColumnDefinitions>
<Rectangle
Stroke="White"
Grid.ColumnSpan="2"
RadiusX="5"
RadiusY="5"
StrokeThickness="3" >
<Rectangle.Fill >
<LinearGradientBrush
EndPoint="0.961,0.858"
StartPoint="0.055,0.163" >
<GradientStop
Color="#FFA4C7F0" />
<GradientStop
Color="#FF4789D6"
Offset="1" />
<GradientStop
Color="#FF69A8F2"
Offset="0.384" />
</LinearGradientBrush>
</Rectangle.Fill>
</Rectangle>
<Grid
Grid.Column="0"
Width="70"
Height="140"
Margin="10" >
<Image
VerticalAlignment="Top"
Source="{Binding Photo}"
Height="60" />
</Grid>
<StackPanel
Grid.Column="1"
Orientation="Vertical"
Margin="0,10,10,0" >
<StackPanel
Orientation="Horizontal"
HorizontalAlignment="Left" >
<TextBlock
Text="First Name:"
Style="{StaticResource CaptionStyle}"
mce_Style="/Edit/{StaticResource CaptionStyle}" />
<TextBlock
Text="{Binding FirstName}"
Style="{StaticResource TextStyle}"
mce_Style="/Edit/{StaticResource TextStyle}" />
</StackPanel>
<StackPanel
Orientation="Horizontal"
HorizontalAlignment="Left" >
<TextBlock
Text="Last Name:"
Style="{StaticResource CaptionStyle}"
mce_Style="/Edit/{StaticResource CaptionStyle}" />
<TextBlock
Text="{Binding LastName}"
Style="{StaticResource TextStyle}"
mce_Style="/Edit/{StaticResource TextStyle}" />
</StackPanel>
<StackPanel
Orientation="Horizontal"
HorizontalAlignment="Left" >
<TextBlock
Text="Department:"
Style="{StaticResource CaptionStyle}"
mce_Style="/Edit/{StaticResource CaptionStyle}" />
<TextBlock
Text="{Binding Department}"
Style="{StaticResource TextStyle}"
mce_Style="/Edit/{StaticResource TextStyle}" />
</StackPanel>
<StackPanel
Orientation="Horizontal"
HorizontalAlignment="Left" >
<TextBlock
Text="Hire Date:"
Style="{StaticResource CaptionStyle}"
mce_Style="/Edit/{StaticResource CaptionStyle}" />
<TextBlock
Text="{Binding HireDate}"
Style="{StaticResource TextStyle}"
mce_Style="/Edit/{StaticResource TextStyle}" />
</StackPanel>
</StackPanel>
</Grid>
</DataTemplate>

Note that above code defines style which is applied to each item inside the CarouselControl.

I hope this article will be helpful to you. Data binding is powerful mechanism to speed up your developement. This article shows how CarouselControl can be used with data binding to create great UI in minutes.

Posted in: SvFx

Flexible Carousel Control

Author: Steve
Posted on: 05 Oct 2009
In this article I want to focus on CarouselControl usage and it's location setups.

Download: Source

If you will search the Internet - you will certainly find numerous examples of carousel control usage. Why? It is a great control for wide range of tasks. Horizontal and vertical menus, image and photo galleries, it is a great way to present data. Carousel control has great usability and it can add special look'n'feel to your web site to make it different.

See it in action below:

Let's take a look how CarouselControl can be used. How simple it is in usage and which features it provides.

Here is an example of simple Ellipse carousel. Note: this example uses images as items, but it is possible to bind any data items.

 <SvUx:CarouselControl 
AlignCenter="True"
ZDepth="100" >
<SvUx:CarouselControl.LocationSetup >
<SvFx:EllipseLocationSetup
Depth="40"
CanUseOpacity="True"
RadiusX="100"
RadiusY="45" />
</SvUx:CarouselControl.LocationSetup>
<SvUx:CarouselControl.Setup >
<SvFx:CycleTransitionSetup
SpeedRatio="2" />
</SvUx:CarouselControl.Setup>
<SvUx:CarouselControl.MouseOverPattern >
<SvFx:ShakeItemPattern />
</SvUx:CarouselControl.MouseOverPattern>
Items go here... </SvUx:CarouselControl>

Here is the screen shot of the result:

Ellipse Carousel

Now let's change several properties and our ellipse carousel will be transformed to slide show:

 <SvUx:CarouselControl 
AlignCenter="True"
ZDepth="100" >
<SvUx:CarouselControl.LocationSetup >
<SvFx:CoverFlowLocationSetup
Depth="40"
CanUseOpacity="True" />
</SvUx:CarouselControl.LocationSetup>
<SvUx:CarouselControl.Setup >
<SvFx:CycleTransitionSetup
SpeedRatio="2" />
</SvUx:CarouselControl.Setup>
<SvUx:CarouselControl.MouseOverPattern >
<SvFx:ShakeItemPattern />
</SvUx:CarouselControl.MouseOverPattern>
Items go here... </SvUx:CarouselControl>

Note: we added MouseOverPattern to the carousel so now it can react to mouse over event.

Here is how it will look like:

CoverFlow

Note: We used CoverFlowLocationSetup instead of EllipseLocationSetup to change items arrangement.

Carousel control contains four specially designed location setups, however it is easy to add new setups.

Now let's return back to the ellipse carousel and make another change. By default topmost item of the Carousel control is defined automatically. For the ellipse carousel it is always item closest to viewer. However we can specify different topmost item index. Let's set TopmostIndex to zero, this means that the first carousel item will be always topmost:

 <SvUx:CarouselControl 
x:Name="ctrlRotatedEllipse"
AlignCenter="True"
VerticalAlignment="Stretch"
HorizontalAlignment="Stretch"
ZDepth="100" >
<SvUx:CarouselControl.LocationSetup >
<SvFx:EllipseLocationSetup
Depth="40"
CanUseOpacity="True"
RadiusX="40"
RadiusY="70"
TopmostIndex="0"
TopmostMode="Specified" />
</SvUx:CarouselControl.LocationSetup>
<SvUx:CarouselControl.Setup >
<SvFx:CycleTransitionSetup
SpeedRatio="2" />
</SvUx:CarouselControl.Setup>
<SvUx:CarouselControl.MouseOverPattern >
<SvFx:ShakeItemPattern />
</SvUx:CarouselControl.MouseOverPattern>
Items go here... </SvUx:CarouselControl>
Rotated Ellipse Carousel

Let's change radius of the Carousel control to zero and we'll get vertical line carousel. This small change can lead to significant modification of the Carousel look'n'feel:

 <SvUx:CarouselControl 
AlignCenter="True"
ZDepth="100" >
<SvUx:CarouselControl.LocationSetup >
<SvFx:EllipseLocationSetup
Depth="40"
CanUseOpacity="True"
RadiusX="0"
RadiusY="70"
TopmostIndex="0"
TopmostMode="Specified" />
</SvUx:CarouselControl.LocationSetup>
<SvUx:CarouselControl.Setup >
<SvFx:CycleTransitionSetup
SpeedRatio="2" />
</SvUx:CarouselControl.Setup>
<SvUx:CarouselControl.MouseOverPattern >
<SvFx:ShakeItemPattern />
</SvUx:CarouselControl.MouseOverPattern>
Items go here... </SvUx:CarouselControl>

Vertical Carousel

Note: one line line of XAML can completely change look'n'feel of the CarouselControl. CarouselControl includes Silverlight 3 powered features: blur, reflection effects, projection and so on.

Do you know any great examples, where Carousel control can be used? Please let me know! :-)

Posted in: SvFx

How to create flashing Logo

Author: Steve
Posted on: 30 Sep 2009
In this post I want to show how you can create animated logo for your web site.

Download: Source

See it in action below:

It is not a secret that organizations want to have unique design for company's web site. And every site starts from a logo!

To add animation to your logo you don't need to redesign it, and you don't need to write to much code. Lets take a look how this can be done with FashLightControl.

E.g. let's imagine we have the following logo for a web site:

Logo

XAML code may look like shown below:

 <Grid 
x:Name="LayoutRoot" >
<Image
Source="Logo.png" />
</Grid>

To add animation to the logo we'll simply place it inside FlashLightControl:

 <Grid 
x:Name="LayoutRoot" >
<FlashLightControl
AutoAdvanceDuration="2000"
StartPoint="0,0"
EndPoint="1,1" >
<Image
Source="Logo.png" />
</FlashLightControl>
</Grid>

We added FlashLightControl to the grid control and then placed our logo inside the control. AutoAdvanceDuration property sets time internval in milliseconds to repeat the animation when elapsed. StartPoint and EndPoint properties can be used to set direction of the animation.

Do you have better ideas? Please post them!

Posted in: SvFx

SvFx 3.0.1 Update

Author: Steve
Posted on: 29 Sep 2009
SvFx 3.0.1 update is now published!


We are glad to announce SvFx 3.0.1 update!

It includes several bug fixes reported plus small improvements added to the CarouselControl and FlashLightControl.

New TopmostIndex and TopmostMode properties are added to the CarouselControl.

Auto advance support is added to the FlashLightControl.

Waiting for your feedback!

Posted in: SvFx Release

SvFx 3.0 is released

Author: Steve
Posted on: 16 Jul 2009
New SvFx 3.0 version is now available!

I'm happy to announce SvFx 3.0 version!

It is fully compatible with Silverlight 3.0!

Read more: SvFx 3.0 What's New

If you want to upgrade to the SvFx 3.0 release, please contact us at support@cellbi.com and we'll help you with upgrading. Note that upgrade price is 50% discount.

We are waiting for your feedback!

Thanks!
Cellbi Software Team

Posted in: SvFx Release

Silverlight3 is out!

Author: Steve
Posted on: 10 Jul 2009
Silverlight3 is out and we work on new SvFx 3.0 version release with some great stuff supporting new Silverlight 3.0 features.

Expect new SvFx 3.0 release published soon.

Below is short change log of new features in SvFx 3.0, we mainly worked on SL3 features support.

Carousel Control

- New Coverflow location setup (completely based on SL3 features) with advanced settings: reflection, blur, angles, item spacings, etc.
- Reflection support for carousel items (check HasReflections check box inside demo)
- Blur support for carousel items (check CanUseBlur check box inside demo)
- Tween support for carousel animation
- Improved animation of items


SlideShowControl

- New pixel shader based patterns: Water, Ripple, Fade and more...


TextEffects

- Support for multi line text animation
- Support for animation by words
- Pixel shader based animations
- Support for style defined text block properties

+ Bug fixes.

I'm very excited about 3.0 version we are going to release soon!

Posted in: Silverlight

ZLib for Silverlight

Author: Steve
Posted on: 02 Jul 2009
ZLib library for Silverlight. Easily read and write ZLib streams. Full source code available.

ZLib streams can be easily read and written via SvZLib library.

Add Cellbi.SvZLib using and use Utils class which contains compression and decompression methods.

Full source code can be downloaded here:

Cellbi.SvZLib-Source

Let me know what you think.

Posted in: Silverlight

Text Effects in Silverlight - It's So Simple

Author: Steve
Posted on: 28 May 2009
In this blog post I'm going to concentrate on how text animation control can be used and customized to create lot's of different text animations.

Download: TextEffectsSample Source

Text animation is powerful tool to present information and catch visitors attention. There are several libraries out there to create text animations in Flex. If you need to create text effects in Silverlight apps - please try SvLite Effects.

See it in action below:

SvLite Effects library providers text effect control to create text animations in Silverlight. The control is easy to use and can be configured in multiple ways to create different text animations.

TextEffectControl can be defined in Xaml as follows:

 <SvUx:TextEffectControl 
x:Name="textEffect"
Text="Text Effects"
FontSize="40"
HorizontalAlignment="Center"
VerticalAlignment="Center" />

You need to set it's Text property, FontSize and it's also possible to use custom Style for the control. In the above code we use TextEffectControlStyle defined inside application resources dictionary.

To start text animation you can use two methods: Show - to show text, and Hide - to hide text. However you also need to define animation parameters for the control. This can be done by setting text effect control Pattern property.

Text effect control Pattern property has TextAnimationPattern type and it defines type of show and hide animations for all text characters.

The following xaml code shows simple text animation pattern, which defines relatively complex animation:

 <SvFx:TextAnimationPattern >
<SvFx:TextAnimationPattern.AnimationSelectors >
<SvFx:AllAnimationGroupSelector >
<SvFx:AllAnimationGroupSelector.AnimationPattern >
<SvFx:ShiftItemPattern
ShowInterval="0.1"
HideInterval="0.1"
SpeedRatio="4"
Shuffle="True"
MoveTween="BackTweenOut"
ShiftMode="FromRandomPoint"
StartVerticalOffset="60"
StartHorizontalOffset="60" />
</SvFx:AllAnimationGroupSelector.AnimationPattern>
</SvFx:AllAnimationGroupSelector>
</SvFx:TextAnimationPattern.AnimationSelectors>
</SvFx:TextAnimationPattern>

AnimationSelectors property defines animation groups and in the above code we use AllAnimationGroupSelector to apply animation to the whole text. In the above code we also use ShiftItemPattern for the selector. ShiftItemPattern is really powerful tool to customize your animations. Shift item pattern contains lot's of properties to customize animation.

Just open App.xaml file from the post's sample code and take a look into all animation patterns defined. It's so simpe!

Posted in: Silverlight

Create Reflection Shader in Silverlight

Author: Steve
Posted on: 25 May 2009
In this post I'm going to post some sample code on how to create reflection shader using new pixel shader feature of Silverlight 3.

Reflection Shader Source

It is easy to create pixel shaders in Silverlight. It's basically C# like code. Language for creating shaders is called HLSL - High Level Shader Language. HLSL is heavily used inside video games to create cool graphics :) At the moment Silverlight doesn't allow you to define vertex shaders, you can do only pixel.

See how it works:

Steps to Create New Pixel Shader:

  1. Create new text file with "fx" extension and place your HLSL code there.
  2. Then compile (not with Visual Studio, but with special effect compiler tool available from DirectX SDK - you can download this from Microsoft web site) your "fx" file to get compiled pixel shader. Compiled pixel shader is placed inside binary file with "ps" extension.
  3. Make sure to include this "ps" file into your project and set it's compile type to "Resource".
  4. And finally create new ".cs" file and place C# shader code there.

Fx File

Effect file should contains HLSL instructions in order to compile. If you are new to HLSL then read HLSL reference here: HLSL Reference it should give you information on language syntax, available data types, operators and functions.

Here is how simplest "fx" file looks like:

sampler2D input : register(s0);

float4 main(float2 uv : TEXCOORD) : COLOR
{
  return tex2D(input, uv);
}

This line: "sampler2D input : register(s0);" defines "input" variable of sampler2D type. This instruction "register(s0)" defines that data for input variable comes from "s0" register. Next main function is defined - it's C like syntax, except for "TEXTCOORD" and "COLOR" - these are HLSL semantics used by effect compiler and GPU. TEXTCOORD means that "uv" parameter contains texture coordinates, which can get values from 0 to 1. Since "uv" variable has float2 data type, it's possible to access it's "u" and "v" components, e.g. "uv.u", "uv.v", or you can use "uv.x", "uv.y". COLOR semantic means that main function returns color data. "text2D" used inside main function's body is HLSL function which returns color data from the given sampler and texture coordinates.

We are going to define Reflect function for our reflection shader. See below:

float4 Reflect(float2 uv : TEXCOORD) : COLOR
{
  float edge = 0.5;
  if (uv.y > edge)
  {
    uv.y = edge - (uv.y - edge);
    return tex2D(input, uv) * uv.y;
  }
  return tex2D(input, uv);
}

 

The code is really simple, if uv.y > 0.5 we reflect uv coordinate and return color data, otherwise we use original texture coordinate to return color data. So now we just call Reflect function from our main:

float4 main(float2 uv : TEXCOORD) : COLOR
{
  return Reflect(uv);
}

To compile fx code you need to run the following command line:
fxc /T ps_2_0 /E main /Fo "Reflection.ps" "Reflection.fx"

For more info see this:
Fxc Tool

You can define pre build action for your project:
"fxc" /T ps_2_0 /E main /Fo "$(ProjectDir)Reflection.ps" "$(ProjectDir)Reflection.fx"

fxc tool will create "Reflection.ps" binary file - include it to your project and set compile type to resource.

 

C# Shader File

Create new C# file, and paste the following code:

 

using System;
using System.Windows.Media.Effects;
using System.Windows;

namespace ReflectionShader
{
  public class ReflectionShader : ShaderEffect
  {
    public ReflectionShader()
    {
      Uri u = new Uri(@"ReflectionShader;component/Reflection.ps", UriKind.Relative);
      PixelShader = new PixelShader() { UriSource = u };
    }

    public static readonly DependencyProperty ElementHeightProperty =
            DependencyProperty.Register("ElementHeight",
            typeof(double), typeof(ReflectionShader),
            new PropertyMetadata(100.0, OnElementHeightChanged));

    static void OnElementHeightChanged(DependencyObject d, 
      DependencyPropertyChangedEventArgs e)
    {
      (d as ReflectionShader).OnElementHeightChanged((double)e.OldValue, (double)e.NewValue);
    }

    protected virtual void OnElementHeightChanged(double oldValue, double newValue)
    {
      PaddingBottom = newValue;
    }

    public double ElementHeight
    {
      get { return (double)base.GetValue(ElementHeightProperty); }
      set { base.SetValue(ElementHeightProperty, value); }
    }
  }
}

Take a look at the code inside ReflectionShader constructor - it sets PixelShader property inherited from ShaderEffect class. "ReflectionShader;component/Reflection.ps" - this string sets relative url to our "ps" file. Since reflection shader needs some space below ui element we use PaddingBottom property inside OnElementHeightChanged method.

 

Hot to Use Pixel Shader

It's really simple. Here is Xaml code:

 <Button 
x:Name="btnReflected"
Width="200"
Height="70" >
<TextBlock
FontWeight="Bold"
FontSize="25"
Text="Reflection" />
<Button.Effect >
<local:ReflectionShader
ElementHeight="70" />
</Button.Effect>
</Button>


That's all.

Posted in: Silverlight

Silverlight Visual States Sample

Author: Steve
Posted on: 06 Apr 2009
In this article I want to illustrate interesting aspect of Silverlight visual states and how they can be used in controls. It is not a secret that one of the key features in Silverlight controls is an ability to declare different states for a control and specify transitions between them.

Each transition between states can take time for animation and often it is necessary to know when transition is really finished.

Let us suppose that we've spent a couple of hours and prepared simple button in Blend.
Something that looks like the following picture ;-)

Visual States Image

The button above consists from 3 parts: LayoutRoot (grid with Width and Height bound to the "Width" and "Height properties of control), Host (button background with color property bound to the "Background" property of control) and Content (green arrow).

You can see how it works here:

Here is the result of such efforts in xaml code, which specifies simple style for the button. The following xaml shows visual state manager and visual states.

 <vsm:VisualStateManager.VisualStateGroups >
<vsm:VisualStateGroup
x:Name="CommonStates" >
<vsm:VisualStateGroup.Transitions >
<vsm:VisualTransition
GeneratedDuration="00:00:00.4000000"
To="MouseOver" />
<vsm:VisualTransition
GeneratedDuration="00:00:00.4000000"
To="Play" />
<vsm:VisualTransition
GeneratedDuration="00:00:00.4000000" />
</vsm:VisualStateGroup.Transitions>
<vsm:VisualState
x:Name="Normal" >
<Storyboard />
</vsm:VisualState>
<vsm:VisualState
x:Name="MouseOver" >
<Storyboard >
<DoubleAnimationUsingKeyFrames
BeginTime="00:00:00"
Duration="00:00:00.4000000"
Storyboard.TargetName="Host"
Storyboard.TargetProperty="(UIElement.Opacity)" >
<SplineDoubleKeyFrame
KeyTime="00:00:00"
Value="1" />
</DoubleAnimationUsingKeyFrames>
</Storyboard>
</vsm:VisualState>
<vsm:VisualState
x:Name="Play" >
<Storyboard >
<DoubleAnimationUsingKeyFrames
BeginTime="00:00:00"
Duration="00:00:00.4000000"
Storyboard.TargetName="Host"
Storyboard.TargetProperty="(UIElement.Opacity)" >
<SplineDoubleKeyFrame
KeyTime="00:00:00"
Value="0" />
</DoubleAnimationUsingKeyFrames>
</Storyboard>
</vsm:VisualState>
</vsm:VisualStateGroup>
</vsm:VisualStateManager.VisualStateGroups>

Now we need to add behaviour logic to this button. It should have 2 methods: Start and Stop.
When mouse is moved over the button the Host should change its opacity. When Stop method is called or button is simply clicked the Content should start rotation - play state of the button.

So, from the point of implementation this can be done in the following way. As you can see from the picture, the Button contains 3 states: "Normal", "MouseOver" and "Play". When mouse pointer is moved over the control we should start transition to the MouseOver state and when the button is clicked we should start transition to the Play state and only after that start the rotation of content.

Please note: "only after that" start the rotation of the content ;) The problem is that transitions between the states can take a time. And if you start rotation of the content immediately after the button is clicked - it will occur in parallel mode with transition and trust me it will look really ugly. So to avoid this we definitely should start the rotation after the transition is finished.

Silverlight has easy way to do exactly this. We can use visual state manager and visual states. Xaml code contains VisualStateManager which declares VisualStates and Transitions. So implement our task we simply need to get access to the VisualStateGroups in the OnApplyTemplate method override and handle several events. Lets take a look how the code would look like.

public override void OnApplyTemplate()
{
  base.OnApplyTemplate();

  FrameworkElement root = GetTemplateChild("LayoutRoot") as FrameworkElement;

  .........

  commonStatesGroup = GetVisualStateGroup(root, "CommonStates");
  HookVisualStateGroupEvents(commonStatesGroup);
}

VisualStateGroup GetVisualStateGroup(FrameworkElement root, string groupName)
{
  if (root == null)
    return null;

  IList groups = VisualStateManager.GetVisualStateGroups(root);
  if (groups == null)
    return null;

  foreach (VisualStateGroup gr in groups)
    if (gr != null && gr.Name == groupName)
      return gr;

  return null;
}

void HookVisualStateGroupEvents(VisualStateGroup group)
{
  if (group == null)
    return;
  group.CurrentStateChanged += group_CurrentStateChanged;
}

void group_CurrentStateChanged(object sender, VisualStateChangedEventArgs e)
{
  if (e.NewState != null && e.NewState.Name == "Play")
    OnStarted();
}

Now let's see what is done in the above code.

First we get access to the "CommonStates" visual group in the OnApplyTemplate method and then simply subscribe to CurrentStateChanged event.

VisualStateChangedEventArgs in the handler gives us only 3 properties: Control, OldState and NewState. However this is all we need in this handler. ;-)

When our event handler is called we can say that control was animated and we know which states animation was done for.

From this point we know that state of the control was changed and we can start content rotation.

Source

I hope this sample will be useful.

Posted in: Silverlight