Friday, June 27, 2008

Silverlight 2 Beta 1 session

Step 1: First I go through 2-3 slides ensuring everybody realises that Silverlight is a cross-browser, cross-platform web technology that utilises .NET in the browser.

Step 2: Demonstrate some apps to give an idea of the kind of rich apps we can build - a subset of these samples.

Step 3: After a slide on what needs to be installed I move to the AGENDA. My AGENDA slide has 5 items on it, which are the following 5 steps (4 to 8).

Step 4: Getting Started aka Hello World.

Step 5: Intro to XAML inc. developer-designer interaction using Blend.

Step 6: HTML Bridge.

Step 7: Networking.

Step 8: IsolatedStorage and OpenFileDialog (i.e. File System Access).

Step 9: Finally, a summary pointing to your one-stop URL for Silverlight:

Thank you to those that attended (or plan to attend) this session.

Animation in-depth with Silverlight 2.0 Beta – Part One

Download Sample Code

In-Depth analysis of animation with Silverlight 2.0 Beta.

Contents [hide]

Introduction to Animation in Silverlight

Animation allows us to create attractive user interfaces. Animation is used to apply dazzling effects such as spin a logo or video, make text scroll, make images grow when the mouse is over them etc. Animation is much like varying the property value over time as far as Silverlight 2.0 is concerned. This will be clear if someone takes a closer look at the animated stuff done in Silverlight/WPF applications. For example, it is possible to make an element grow by increasing its Width and Height or changing its Color value or its opacity in a specified duration.

The Size, Color and Value of an element can be varied over a period of time by setting the duration in the Storyboard. Storyboard controls animations with a timeline, and provides object and property targeting information for its child animations. The real definition of animation is - "An illusion that is created by quickly cycling through a series of images". Our brain perceives the group of images as a single changing scene. In Television broadcast or Film this illusion is created using cameras that record a number of pictures - frames - each slightly different from the last displayed, in a specific amount of time by capturing them in a timeline.

Silverlight too has its timeline to specify what actions to perform at specified time intervals. In Silverlight all animations inherit from the Timeline object; therefore all animations are specialized type of Timelines. A timeline represents a segment of time. To specify the length of the segment, when it should start and stop, how many times it will repeat, how fast time progresses in that segment, Silverlight uses Timelines.

Before digging deep into animation, here are two sample programs to give you an idea on what animations do in Silverlight, or what can be done with animations. This is just a simple animated sample to show you the animation in action. You can modify this code to make it more effective. The sample program below animates two videos one after another:

Figure 1: Silverlight Animation in Action

Silverlight Animation in Action

The above is the first video in this application, which has been scaled, translated and rotated to get the animated effect. After this video finishes another one starts by spinnig over the first video. Check the picture of this animation:

Figure 2: The second animation in action

The second animation in action

You should be excited by now seeing the power of Silverlight animation. This application contains three MediaElements. Two of them have been animated and I have used the other for a five seconds video which shows the text “Powered by Silverlight” together with the Silverlight logo. The complete code is shown below, but don’t dig deeper into this before learning the basics, which will come next in this article.

Listing 1: Page.xaml

  1. <UserControl
  2. xmlns=""
  3. xmlns:x=""
  4. x:Class="SilverlightVideoAnimation3.Page"
  5. Loaded="Page_Loaded"
  6. Width="1024" Height="680"
  7. xmlns:d=""
  8. xmlns:mc=""
  9. mc:Ignorable="d">
  10. <UserControl.Resources>
  11. <Storyboard x:Name="VideoTimeline">
  12. <DoubleAnimationUsingKeyFrames
  13. Storyboard.TargetName="mediaElement"
  14. Storyboard.TargetProperty="(UIElement.Opacity)"
  15. BeginTime="00:00:00">
  16. <SplineDoubleKeyFrame KeyTime="00:00:00" Value="0"/>
  17. <SplineDoubleKeyFrame KeyTime="00:00:02" Value="1"/>
  18. DoubleAnimationUsingKeyFrames>
  19. <DoubleAnimationUsingKeyFrames
  20. Storyboard.TargetName="mediaElement"
  21. Storyboard.TargetProperty="(UIElement.RenderTransform).
  22. (TransformGroup.Children)[0].(ScaleTransform.ScaleX)"
  23. BeginTime="00:00:00">
  24. <SplineDoubleKeyFrame KeyTime="00:00:02" Value="1"/>
  25. <SplineDoubleKeyFrame KeyTime="00:00:03" Value="1.5"/>
  26. <SplineDoubleKeyFrame KeyTime="00:00:07" Value="1.5"/>
  27. <SplineDoubleKeyFrame KeyTime="00:00:09" Value="3.594"/>
  28. DoubleAnimationUsingKeyFrames>
  29. <DoubleAnimationUsingKeyFrames
  30. Storyboard.TargetName="mediaElement"
  31. Storyboard.TargetProperty="(UIElement.RenderTransform)
  32. .(TransformGroup.Children)[0].(ScaleTransform.ScaleY)"
  33. BeginTime="00:00:00">
  34. <SplineDoubleKeyFrame KeyTime="00:00:02" Value="1"/>
  35. <SplineDoubleKeyFrame KeyTime="00:00:03" Value="1.5"/>
  36. <SplineDoubleKeyFrame KeyTime="00:00:07" Value="1.5"/>
  37. <SplineDoubleKeyFrame KeyTime="00:00:09" Value="3.594"/>
  38. DoubleAnimationUsingKeyFrames>
  39. <DoubleAnimationUsingKeyFrames
  40. Storyboard.TargetName="mediaElement"
  41. Storyboard.TargetProperty="(UIElement.RenderTransform)
  42. .(TransformGroup.Children)[3].(TranslateTransform.X)"
  43. BeginTime="00:00:00">
  44. <SplineDoubleKeyFrame KeyTime="00:00:03" Value="0"/>
  45. <SplineDoubleKeyFrame KeyTime="00:00:04" Value="56"/>
  46. <SplineDoubleKeyFrame KeyTime="00:00:05.9000000" Value="-135"/>
  47. <SplineDoubleKeyFrame KeyTime="00:00:07" Value="-196"/>
  48. <SplineDoubleKeyFrame KeyTime="00:00:09" Value="-62"/>
  49. DoubleAnimationUsingKeyFrames>
  50. <DoubleAnimationUsingKeyFrames Storyboard.TargetName="mediaElement"
  51. Storyboard.TargetProperty="(UIElement.RenderTransform)
  52. .(TransformGroup.Children)[3].(TranslateTransform.Y)"
  53. BeginTime="00:00:00">
  54. <SplineDoubleKeyFrame KeyTime="00:00:03" Value="0"/>
  55. <SplineDoubleKeyFrame KeyTime="00:00:04" Value="1"/>
  56. <SplineDoubleKeyFrame KeyTime="00:00:05.9000000" Value="168"/>
  57. <SplineDoubleKeyFrame KeyTime="00:00:07" Value="-41"/>
  58. <SplineDoubleKeyFrame KeyTime="00:00:09" Value="59.5"/>
  59. DoubleAnimationUsingKeyFrames>
  60. <DoubleAnimationUsingKeyFrames Storyboard.TargetName="mediaElement"
  61. Storyboard.TargetProperty="(UIElement.RenderTransform)
  62. .(TransformGroup.Children)[2].(RotateTransform.Angle)"
  63. BeginTime="00:00:00">
  64. <SplineDoubleKeyFrame KeyTime="00:00:05.9000000" Value="0"/>
  65. <SplineDoubleKeyFrame KeyTime="00:00:07" Value="360"/>
  66. DoubleAnimationUsingKeyFrames>
  67. <DoubleAnimationUsingKeyFrames Storyboard.TargetName="mediaElement1"
  68. Storyboard.TargetProperty="(UIElement.RenderTransform)
  69. .(TransformGroup.Children)[3].(TranslateTransform.X)"
  70. BeginTime="00:00:00">
  71. <SplineDoubleKeyFrame KeyTime="00:00:30" Value="-465"/>
  72. <SplineDoubleKeyFrame KeyTime="00:00:32" Value="-545"/>
  73. <SplineDoubleKeyFrame KeyTime="00:00:35" Value="-518.5"/>
  74. DoubleAnimationUsingKeyFrames>
  75. <DoubleAnimationUsingKeyFrames Storyboard.TargetName="mediaElement1"
  76. Storyboard.TargetProperty="(UIElement.RenderTransform)
  77. .(TransformGroup.Children)[0].(ScaleTransform.ScaleX)"
  78. BeginTime="00:00:00">
  79. <SplineDoubleKeyFrame KeyTime="00:00:30" Value="1"/>
  80. <SplineDoubleKeyFrame KeyTime="00:00:32" Value="1"/>
  81. <SplineDoubleKeyFrame KeyTime="00:00:35" Value="4.993"/>
  82. DoubleAnimationUsingKeyFrames>
  83. <DoubleAnimationUsingKeyFrames Storyboard.TargetName="mediaElement1"
  84. Storyboard.TargetProperty="(UIElement.RenderTransform)
  85. .(TransformGroup.Children)[0].(ScaleTransform.ScaleY)"
  86. BeginTime="00:00:00">
  87. <SplineDoubleKeyFrame KeyTime="00:00:30" Value="1"/>
  88. <SplineDoubleKeyFrame KeyTime="00:00:32" Value="1"/>
  89. <SplineDoubleKeyFrame KeyTime="00:00:35" Value="5.364"/>
  90. DoubleAnimationUsingKeyFrames>
  91. <DoubleAnimationUsingKeyFrames Storyboard.TargetName="mediaElement1"
  92. Storyboard.TargetProperty="(UIElement.RenderTransform)
  93. .(TransformGroup.Children)[3].(TranslateTransform.Y)"
  94. BeginTime="00:00:00">
  95. <SplineDoubleKeyFrame KeyTime="00:00:30" Value="0"/>
  96. <SplineDoubleKeyFrame KeyTime="00:00:32" Value="0"/>
  97. <SplineDoubleKeyFrame KeyTime="00:00:35" Value="177"/>
  98. DoubleAnimationUsingKeyFrames>
  99. <DoubleAnimationUsingKeyFrames Storyboard.TargetName="mediaElement1"
  100. Storyboard.TargetProperty="(UIElement.RenderTransform)
  101. .(TransformGroup.Children)[2].(RotateTransform.Angle)"
  102. BeginTime="00:00:00">
  103. <SplineDoubleKeyFrame KeyTime="00:00:30" Value="0"/>
  104. <SplineDoubleKeyFrame KeyTime="00:00:32" Value="0"/>
  105. <SplineDoubleKeyFrame KeyTime="00:00:35" Value="360"/>
  106. DoubleAnimationUsingKeyFrames>
  107. Storyboard>
  108. UserControl.Resources>
  109. <Grid x:Name="LayoutRoot" >
  110. <Grid.Background>
  111. <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
  112. <GradientStop Color="#FFFFFFFF" Offset="0.554"/>
  113. <GradientStop Color="#FF282828" Offset="0"/>
  114. <GradientStop Color="#FF595858" Offset="1"/>
  115. LinearGradientBrush>
  116. Grid.Background>
  117. <MediaElement HorizontalAlignment="Stretch"
  118. Margin="281.837005615234,137.998992919922,432.832000732422,0"
  119. VerticalAlignment="Top" Opacity="1" Source="Media/racecar.wmv"
  120. d:LayoutOverrides="HorizontalAlignment, Height" x:Name="mediaElement"
  121. RenderTransformOrigin="0.5,0.5" Height="93.998">
  122. <MediaElement.RenderTransform>
  123. <TransformGroup>
  124. <ScaleTransform/>
  125. <SkewTransform/>
  126. <RotateTransform/>
  127. <TranslateTransform/>
  128. TransformGroup>
  129. MediaElement.RenderTransform>
  130. MediaElement>
  131. <MediaElement Height="81.126" HorizontalAlignment="Right" Margin="0,0,0,0"
  132. VerticalAlignment="Top" Width="144" Source="Media/Halo.wmv"
  133. d:LayoutOverrides="Height" Position="00:00:16"
  134. RenderTransformOrigin="0.5,0.5" x:Name="mediaElement1">
  135. <MediaElement.RenderTransform>
  136. <TransformGroup>
  137. <ScaleTransform/>
  138. <SkewTransform/>
  139. <RotateTransform/>
  140. <TranslateTransform/>
  141. TransformGroup>
  142. MediaElement.RenderTransform>
  143. MediaElement>
  144. <MediaElement x:Name="MediaElement3" Height="98"
  145. HorizontalAlignment="Right"
  146. Margin="0,0,17,137" VerticalAlignment="Bottom"
  147. Width="127" Source="Media/poweredby_silverlight.wmv"
  148. Position="00:00:05">
  149. MediaElement>
  150. Grid>

Listing 2: Page.xaml.cs

  1. using System;
  2. using System.Windows;
  3. using System.Windows.Controls;
  4. using System.Windows.Documents;
  5. using System.Windows.Ink;
  6. using System.Windows.Input;
  7. using System.Windows.Media;
  8. using System.Windows.Media.Animation;
  9. using System.Windows.Shapes;
  10. namespace SilverlightVideoAnimation3
  11. {
  12. public partial class Page : UserControl
  13. {
  14. public Page()
  15. {
  16. // Required to initialize variables
  17. InitializeComponent();
  18. }
  19. private void Page_Loaded(object sender, EventArgs e)
  20. {
  21. VideoTimeline.Begin();
  22. }
  23. }
  24. }

I’m not explaining this code here because earlier I’ve suggested you to take a look at the basics of the animation, before digging into this. You’ll see more in the video animation section of this article.

Animation types

Silverlight provides two types of animation:

  • From/To/By animations.
  • key-frame animations.

Classes that are derived from Timeline provide animation functionality. Here's the inheritance hierarchy:

  • System.Object
  • System.Windows.DependencyObject
  • System.Windows.Media.Animation.Timeline
  • System.Windows.Media.Animation.ColorAnimation
  • System.Windows.Media.animation.ColorAnimation.ColorAnimationUsingKeyFrames
  • System.Windows.Media.Animation.DoubleAnimation
  • System.Windows.Media.Animation.DoubleAnimationUsingKeyFrames
  • System.Windows.Media.Animation.ObjectAnimationUsingKeyFrames
  • System.Windows.Media.Animation.PointAnimation
  • System.Windows.Media.Animation.PointAnimationUsingKeyFrames
  • System.Windows.Media.Animation.Storyboard

When using animations, several of the following properties are needed:

  • AutoReverse: Reverses the animation if it has ended (i.e., moves the element back to where it started).
  • Duration: The duration of an animation, using the syntax hh:mm:ss (hours, minutes, seconds).
  • From: The start value for the animation.
  • To: The end value for the animation.
  • By: A relative value indicating by how much to change the animation (an alternative approach for using To).
  • RepeatBehavior: What to do if the animation has ended; you can provide a (total) duration, a number of times to repeat, or mark it Forever if the animation should repeat endlessly.
  • Storyboard.TargetName: The name of the element that needs to be animated (therefore, we needed to assign a name).
  • Storyboard.TargetProperty: The property of the element that needs to be animated.

To programmatically control the animation, the following methods are used:

  • Begin: Initiates the Storyboard.
  • Pause: Pauses the Storyboard.
  • Resume: Resumes a paused Storyboard.
  • Stop: Stops the Storyboard.
  • Seek: Skips to a specific part of the Storyboard animation.

A key-frame animation animates between a series of values specified using key-frame objects. Key-frame animations are more powerful than From/To/By animations because any number of target values can be specified and we can even control their interpolation method. We’ll see the power of key-frame animation in a moment.

ColorAnimationUsingKeyFrames animates the color of a SolidColorBrush or GradientBrush, DoubleAnimationUsingKeyFrames animates the width and height of FrameworkElements, PointAnimationUsingKeyFrames animates the center position of an EllipseGeometry, ObjectAnimationUsingKeyFrames animates the Fill property from one GradientBrush to another.

In key-fame animations a certain stage in the application must be reached. For example, an object needs to have specific positions. When a key-frame is reached a certain object value must be met. Every key frame needs at least two values or attributes:

  • KeyTime: At what time the key-frame will come into effect.
  • Value: The value that needs to be reached at a given time.

In a Timeline where you have a keyframe after half second with a value of 20, and another one after 1 and half seconds with value of 40, the assigned value of these two frames will be animated between them. How this value is animated from 20 to 40 will be defined by the second keyframe. There are different ways to interpolate the value, and the second keyframe needs to confirm which of these methods is used. Silverlight currently supports three methods: Linear, Discrete and Spline. Here’s an example of key frame animation. This example uses three rectangles to demonstrate Spline, Discrete and Linear key-frames. To create it, open Microsoft Expression Blend 2.5 March Preview.

Figure 3: Opening Expression Blend

Opening Expression Blend

Change the Grid’s background to LinearGradientBrush. In this case Grid is our root element. Create three rectangles inside the section. Change also the background of the rectangles to LinearGradientBrush. By now, you should have change your visual interface to something like the following.

Figure 4: Visual Interface for Silverlight KeyFrameAnimations

Visual Interface for Silverlight KeyFrameAnimations

Add a Storyboard by clicking the + button which resides under the objects and timeline tab. Select rectangle1 in the Objects and Timeline panel. Translate the x property to 50 when Playhead position is in 0:00.000. Again translate the x property to 544 and the Playhead position will be in 0:01.000. At last set the x property to 0 again when the Playhead position is 0:03.000. Now select rectangle2, move the timeline where Playhead position is 0:00.300 and translate the x property of the TranslateTransform that will be applied to our second rectangle. Set the x value to 544 when the Playhead position is 0:01.000 and set it to 0 when Playhead position is 0:03.000. Do the same for the rectangle3. After completing this step you should have a timeline like the following.

Figure 5: KeyFrameAnimations Timeline

KeyFrameAnimations Timeline

This will generate the following Xaml behind the scenes, in the section:

Listing 3: Page.xaml

  1. <Storyboard x:Name="Storyboard1">
  2. <DoubleAnimationUsingKeyFrames Storyboard.TargetName="rectangle1"
  3. Storyboard.TargetProperty="(UIElement.RenderTransform)
  4. .(TransformGroup.Children)[3].(TranslateTransform.X)"
  5. BeginTime="00:00:00">
  6. <SplineDoubleKeyFrame KeyTime="00:00:00" Value="0"/>
  7. <SplineDoubleKeyFrame KeyTime="00:00:01" KeySpline="0.6,0 0.9,0" Value="544"/>
  8. <SplineDoubleKeyFrame KeyTime="00:00:03" KeySpline="0.6,0 0.9,0" Value="0"/>
  9. DoubleAnimationUsingKeyFrames>
  10. <DoubleAnimationUsingKeyFrames Storyboard.TargetName="rectangle2"
  11. Storyboard.TargetProperty="(UIElement.RenderTransform)
  12. .(TransformGroup.Children)[3].(TranslateTransform.X)"
  13. BeginTime="00:00:00">
  14. <SplineDoubleKeyFrame KeyTime="00:00:00.3000000" Value="282"/>
  15. <SplineDoubleKeyFrame KeyTime="00:00:01" Value="540"/>
  16. <SplineDoubleKeyFrame KeyTime="00:00:03" Value="0"/>
  17. DoubleAnimationUsingKeyFrames>
  18. <DoubleAnimationUsingKeyFrames Storyboard.TargetName="rectangle3"
  19. Storyboard.TargetProperty="(UIElement.RenderTransform)
  20. .(TransformGroup.Children)[3].(TranslateTransform.X)"
  21. BeginTime="00:00:00">
  22. <SplineDoubleKeyFrame KeyTime="00:00:00.3000000" Value="284"/>
  23. <SplineDoubleKeyFrame KeyTime="00:00:01" Value="542"/>
  24. <SplineDoubleKeyFrame KeyTime="00:00:03" Value="0"/>
  25. DoubleAnimationUsingKeyFrames>
  26. Storyboard>

Now change the to in the last section of the DoubleAnimationUsingKeyFrames. Discrete key frames, like DiscreteDoubleKeyFrame, create sudden jumps between values. For example, if the rectangle is at the starting position, it can suddenly appear at the 500 position. The animated property won’t change until the key frame's key time is reached, at which point the animated property goes suddenly to the target value.

Change the to in the middle DoubleAnimationUsingKeyFrames section. Add the KeySpline property in and your code should look like this:

  1. <Storyboard x:Name="Storyboard1">
  2. <DoubleAnimationUsingKeyFrames Storyboard.TargetName="rectangle1"
  3. Storyboard.TargetProperty="(UIElement.RenderTransform)
  4. .(TransformGroup.Children)[3].(TranslateTransform.X)"
  5. BeginTime="00:00:00">
  6. <SplineDoubleKeyFrame KeyTime="00:00:00" Value="50"/>
  7. <SplineDoubleKeyFrame KeyTime="00:00:01" KeySpline="0.6,0 0.9,0" Value="544"/>
  8. <SplineDoubleKeyFrame KeyTime="00:00:03" KeySpline="0.6,0 0.9,0" Value="0"/>
  9. DoubleAnimationUsingKeyFrames>
  10. <DoubleAnimationUsingKeyFrames Storyboard.TargetName="rectangle2"
  11. Storyboard.TargetProperty="(UIElement.RenderTransform)
  12. .(TransformGroup.Children)[3].(TranslateTransform.X)"
  13. BeginTime="00:00:00">
  14. <LinearDoubleKeyFrame KeyTime="00:00:00.3000000" Value="10.2"/>
  15. <LinearDoubleKeyFrame KeyTime="00:00:01" Value="544"/>
  16. <LinearDoubleKeyFrame KeyTime="00:00:03" Value="0"/>
  17. DoubleAnimationUsingKeyFrames>
  18. <DoubleAnimationUsingKeyFrames Storyboard.TargetName="rectangle3"
  19. Storyboard.TargetProperty="(UIElement.RenderTransform)
  20. .(TransformGroup.Children)[3].(TranslateTransform.X)"
  21. BeginTime="00:00:00">
  22. <DiscreteDoubleKeyFrame KeyTime="00:00:00.3000000" Value="10"/>
  23. <DiscreteDoubleKeyFrame KeyTime="00:00:01" Value="544"/>
  24. <DiscreteDoubleKeyFrame KeyTime="00:00:03" Value="0"/>
  25. DoubleAnimationUsingKeyFrames>
  26. Storyboard>

Run the application and check the difference between them.

Principles of animation

Here I’m going to present the principles of animation extracted from the book MS Expression Blend Bible. It’s quite an effective concept to bring liveliness to your animated application.

Adding realism is a key factor when creating an eye catching animation. To me, as a developer of Silverlight applications, everyone should follow the principles of animation to add realism and effectiveness when applying animation to their application. As far as storytelling is concerned animation, for example when developing a game your animation may proceed like this:

  • Creating a script for storyboard.
  • Record voices, Sound effects and background music, and layer them together to create a soundtrack.
  • Designing visuals in more detail.
  • Animate those visuals.

If someone wants to put emphasis on adding interest and realism behind animation, the following principles should be kept in mind:

Squash and stretch

When an object is squashed, its volume should remain equal to the volume it has when it is not squashed. Squashing and stretching a bouncing ball can add realism, appeal or both. When two objects bump together, they both squash inward at the point of impact and stretch in a perpendicular direction, unless they are made of a completely rigid material. Then they regain their original shape. It’s important as an animator to always give the squashed and stretched shape the same volume as the original shape. The object shouldn’t appear to gain any mass.

Timing and motion

This is where user’s attentions are attracted and gives sense of weight, importance and anticipation to an object. Timing and motion are an integral part of every animation. Timing and motion can give a sense of the weight of an object. When an object takes a long time to get going and to stop, it gives the impression that it’s heavier than something that takes less time. User's attention can be attracted using motion in two ways: A moving object or character can attract the attention if everything else in the scene is still and a still object can attract attention if everything else in the scene is moving.


Plays the big part when the attention of the audience to the area of the screen containing the information is purposely brought. In animation, staging is the process by which the eye is drawn to the part of the screen that the animator wants to emphasize. For example, if a character lifts an eyebrow to indicate that he’s got a plan, you may want to show the action in a close-up so that the audience notices it.

Overlapping action and follow-through

It's handy when motion is given a practical or appearance of reality. Starting one action before another action is complete. Action that continues to occur after an action has mostly completed. For example, follow-through occurs when a ball is caught by a hand and the hand moves back to indicate that the ball pushed the hand back. Or when a walking character takes a step and his hand continues to swing.


Animating motions along arcs, because most objects in nature don't move along a perfect straight line, this is when arcs are animated along motions. In the natural world, living things usually don’t move in straight lines. When we walk, we move up and down in an arc as we take a step, then straighten up and take the next. All animals move in an arc motion, some more than others. And the trees move with the wind in an arc. Arcs occur both visually and in time. Water in a stream is sometimes slow, sometimes fast. Wind blows, and then diminishes. Rabbits hop, and then stop. Varying the timing and the visual motion of your animation in a natural way can enhance the feeling that you may want it to convey.

These are the elements of animation that must be structured in an organized way in order to give attractiveness and realism no matter what platforms you are working on.


In the first part of this series we presented the main concepts of animations with Silverlight. We talked about animation types and discussed the key animation principles that you must keep in mind when developing rich applications. In the next part, we’ll dive deep into Storyboards.


is yet another Silverlight assembly with no direct counterpart in the full framework, but with tons of stuff inside (as evidenced by its size on disc and by the 21 namespaces!) that makes it the 2nd largest assembly. You can think of it as the brick that gives Silverlight its WPF UI. Its namespaces come from various v2.0 and v3.0 desktop assemblies as listed below (and it is in my opinion a prime candidate for refactoring):

-System.Net namespace with WebClient plus 6 related classes comes from the desktop's System.dll (!)

- System.ComponentModel comes from System.dll (! again) and is basically the BackgroundWorker implementation.

- 5 of its namespaces (System.Windows.Controls.Primitives, System.Window.Data, System.Windows.Documents, System.Windows.Resources, System.Windows.Shapes) and the System.ComponentModel.DesignerProperties class map to the desktop's PresentationFramework.dll

- 3 of its namespaces (System.Collections.ObjectModel, System.Collections.Specialized, System.Threading) map to WindowsBase.dll.

- 2 of its namespaces (System.Windows.Ink, System.Windows.Media.Imaging) map to the desktop's PersentationCore.dll.

- System.Windows namespace has a total of 61 types, coming from homonymous namespaces in PresentationCore.dll (e.g. FontStyle, RoutedEventHandler) and PresentationFramework.dll (e.g. Application, FrameworkElement) and WindowsBase.dll (e.g. DependencyProperty, Point) and also introduces some new types (e.g. AssemblyPart, ErrorType).

- System.Windows.Markup namespace with 2 types from WindowsBase.dll, 2 from PresentationFramework.dll and 1 from PresentationCore.dll.

- System.Windows.Media namespace which maps to PresentationCore.dll except for Matrix class from WindowsBase.dll and 5 new Silverlight types (MediaElementState, TimelineMarkerCollection plus 2 relatives and VideoBrush).

- System.Windows.Input largely maps to PresentationCore.dll, except for 2 classes (Key and ModifierKeys) from WindowsBase.dll and 1 class (KeyboardNavigationMode) from PresentationFramework.dll. There is also one new class in there: StylusInfo.

- System.Windows.Controls namespace has 24 types that come from PresentationFramework.dll (same namespace name of course). It also has 2 types (MultiScaleImage, MultiScaleSubImage) that make up the DeepZoom feature. It also has 3 types (2 from System.Windows.Forms.dll plus 1 brand new) that make up the OpenFileDialog feature.

- System.IO.IsolatedStorage.ApplicationSettings class has no counterpart in the desktop world and was touched upon here (scroll to the bottom).

- System.Windows.Interop namespace with 3 classes (Content, Settings and SilverlightHost) that is all new in Silverlight framework (even though that namespace name exists in various other WPF assemblies).

12. and 13. System.Windows.Controls.dll and System.Windows.Controls.Extended.dll
The overwhelming majority of the Silverlight controls reside in the System.Windows.Controls.dll assembly. The Extended.dll adds the Calendar, DatePicker, Slider and WatermarkedTextBox.

14. System.Windows.Controls.Data.dll
This adds a control not available at present in WPF: the Silverlight DataGrid. For all things DataGrid-related

Silverlight Example Apps

(shows the DeepZoom feature in a public released site)
2. Silverlight Airlines (gets you thinking of great user experience for booking a flight)
3. Cameras (another example of great user experience for shopping online scenario)
4. Image Snipper (shows graphics and interaction you would only expect from a desktop app)
5. Video Puzzle (combination of a game with video elements)

...then before jumping into code, it is worth showing some of the controls that are available and also how they can be skinned (templated):
6. Control Demo (not all of them, but gives you an idea)
7. Corina's control skins Flat, Bubbly, Red, Rough.

...if you are looking for a sample that combines skinning, the OpenFileDialog, IsolatedStorage and also throws in a bit of extensibility, do check this out:
8. Calculator (get its story from the author's blog post)

9. a great business application that is almost indistinguishable from a local client and has only recently been made available is the Healthcare Demo (built in the UK).

What publically available Silverlight application(s) float your boat?

Thursday, December 20, 2007

Supporting Full Screen Mode with Silverlight

One of the nice features that Silverlight supports is the ability to go "full screen" and effectively take over the entire screen of a computer (hiding everything else from sight - including the browser frame). This can be very useful when building immersive UI experiences, games, rich video players, etc.
For a nice example of this feature in action, make sure to check out the Fox Movies Sample on

Once the page loads and the movie starts playing, double-click on the video surface in the middle to switch into full-screen mode (note: the screen-shot above is not in full-screen but rather browser mode). You can then hit the escape key to switch back into normal browser viewing.
How to Implement Full Screen Mode with Silverlight 1.1 using .NET
One of the questions I've seen a few people ask is "how can you implement full screen-mode when building Silverlight applications using .NET?" The good news is that the answer is actually pretty easy:
1) First add an input driven event handler to your application (for example: a mouse down or keyboard event handler). For security reasons Silverlight doesn't allow developers to switch an application into full-screen mode on first application load (you don't want an application to spoof you). So you'll instead need to trigger full-screen mode in response to a user action.
2) Within your input event handler set the BrowserHost.IsFullScreen property to true (note: the BrowserHost class lives within the System.Windows.Interop namespace). This will cause Silverlight to switch into full screen mode. Setting this property to false will return it back to normal browser mode.
Simple Full Screen Mode Sample
You can download a simple Silverlight full screen-mode sample I put together written in C# here.
When you run the sample it will load a super simple Silverlight application within the browser and display a text message prompting you to click it to switch into full-screen mode:

When you switch into full-screen mode, Silverlight will display a user message blurb that will pop-up on the screen for a few seconds and instruct the user that they can press the escape key to switch back into browser mode. After a few seconds this message will disappear and only your content will be visible. In my sample above I also allow the user to click on the "Click to Return to Browser" text and switch back into browser mode as well.
Walkthrough the Simple Full Screen Mode Code
The code to implement the above sample is pretty simple.
To begin with we can open and edit the root .XAML file for the application, and add a UI element to it that we want to use to trigger the full-screen mode. In the sample above I used a control that I named "MyMessage". Below is all of the XAML for the entire application:

Within the application's Page_Loaded() event handler above I am wiring up two event handlers:
MyMessage_MouseLeftButtonDown - This event handler will execute anytime a user clicks on the TextBlock message control I added into my XAML file. Within this event handler I'm simply toggling the BrowserHost.IsFullScreen property to true or false depending on whether or not it is already in full screen mode.
BrowserHost_FullScreenChange - This event handler will execute anytime Silverlight switches between full screen and browser mode. It provides a good place to add logic to update the UI when this happens. In the example above I am changing the text on the TextBlock control. I could also have optionally resized controls and/or moved them around the screen to new coordinate positions. Currently the Silverlight 1.1 Alpha doesn't have layout manager support, so controls won't automatically re-position unless you write code to manage this yourself (don't worry - layout manager controls for Silverlight like in the desktop WPF version are coming).
In addition to the IsFullScreen property, BrowserHost class has a number of additional properties and events that are very useful:

Silverlight Tutorial - Color Animations

In this tutorial, I'm going to show you how to use Silverlight's Storyboard and ColorAnimation XAML tags to create custom color animations. Color animations are commonly used on input controls like buttons to give visual feedback that the cursor is over the control or when the button has been pressed. This tutorial will show a couple of simple examples that can easily be extended to complex controls and animations.

The examples in this post were built using Visual Studio 2008 beta 2, Silverlight 1.1 Alpha Refresh, and C#. For information on where to download these, please visit our previous tutorial Getting Started With Silverlight.

We'll start by defining the XAML for the rectangle.

Here we've defined a very simple red rectangle. Since we want the color to change when the user enters or leaves the control with the cursor, we've defined event handlers for each of these. The code inside these event handlers is located in the C# code behind and will be explained a little later. Now that we have the rectangle defined, let's create an animation to change the color of the rectangle when the user enters it with the mouse cursor.

The first thing you might notice here is the tag. This tag holds a collection of Storyboards and is located directly after the opening Canvas tag. Inside this tag is where we'll be placing the Storyboards that will control our color animations. The first Storyboard we're going to make will change the color of the rectangle when the user enters the control with the mouse. In order to control the Storyboard from the C# code-behind, you'll have to first give it a name. I named mine "mouseEnter". Next we add a ColorAnimation inside the Storyboard. The first attribute we set is Duration, which is how long the animation will run - in this case, 1 second. Next, we set the end result of the animation. I want my rectangle to fade from red to black, so I set To to "#000000". The next thing we set is the Storyboard.TargetName, which is the name of the object we want to modify. This has to be set to the same thing that we named the rectangle, in this case "myRectangle". Storyboard.TargetProperty is the property the animation will be changing, which in this case is the fill color. It might seem like a complicated way to address the rectangle's fill color, but it's necessary. If we expanded out the rectangle to use a SolidColorBrush it might make a little more sense:

So in the attribute , "(Shape.Fill)" refers to and "(SolidColorBrush.Color)" is the Color attribute of . All right, the storyboard and animation are done and ready to be run. Let's create some C# code that will handle the events.
private void MyRectangleMouseEnter(object sender, EventArgs e){ this.mouseEnter.Begin();}
If you remember, we added a MouseEnter event to our XAML code and told it to execute the method MyRectangleMouseEnter. All this function does is to start the Storyboard we named "mouseEnter". If you build and preview your project, you should get something that looks like the following:
If you ask me, that's not very interesting. Let's add in the XAML code to make the rectangle fade back to red when the mouse leaves the control.

To make the rectangle fade back to red, I simply added another Storyboard to the canvas resources. The only thing different from the previous ColorAnimation is that To is now set to red (#FF0000), instead of black (#000000). Just like with the previous storyboard, we'll going to need some C# code to run the animation. This time, the function is hooked up to the rectangle's MouseLeave event.
private void MyRectangleMouseLeave(object sender, EventArgs e){ this.mouseLeave.Begin();}
That's it. Now we have a rectangle that fades to black when the mouse enters it and fades back to red when the mouse leaves.
We've only barely touched the surface for the possibilities of what a color animation is capable of - but hopefully this tutorial will provide you with a launching point for your own complex (and much more interesting) animations.

Silverlight and Javascript Interaction

Silverlight is a relatively new client side technology released by Microsoft, but already people are finding the need to communicate between their Silverlight applications and Javascript. This tutorial will go through all the code required to call Javascript functions from Silverlight and vice-versa.
All the Silverlight code and examples were created using the 1.1 Alpha Refresh. Before you can use the example application below, you'll need to download the runtime (if you haven't already). If you're new to Silverlight, check out our introductory tutorial for information on what to download and how to get started.

Before we jump into code, let's look at an example of some communication between Silverlight and Javascript. The application on the left was created using Silverlight, the one on the right was made using HTML and CSS. When one of the buttons on the left is clicked, a message will be displayed on the right indicating that. The same thing happens when a button on the right is clicked.

So let's see how something like this is done. We'll start with the hard one - calling a Javascript function from Silverlight. There's no direct way (that I know of) to simply call a Javascript function directly from the Silverlight code behind. What we have to do is create events and attach to them from the Javascript code. This isn't a lot of work, but being able to call them directly would be a nice feature to have. So let's look at some
C# code behind that creates the events.

using System;using System.Windows;using System.Windows.Controls;using System.Windows.Documents;using System.Windows.Input;using System.Windows.Browser;namespace SilverlightJavascript{ [Scriptable] public partial class Page : Canvas { [Scriptable] public event EventHandler ButtonAClicked; [Scriptable] public event EventHandler ButtonBClicked; [Scriptable] public event EventHandler ButtonCClicked; public void Page_Loaded(object o, EventArgs e) { // Required to initialize variables InitializeComponent(); WebApplication.Current.RegisterScriptableObject( "SilverlightApp", this); } }}

Since my Silverlight application has three buttons, I created three events - one for each button. They're created and used exactly like they are in an ordinary C# Windows application. One difference I'm sure you noticed is the [Scriptable] attribute above the definition of the class and each event. This lets Silverlight know that this class and these events should be accessible from the Javascript code. The next thing you might have noticed is the RegisterScriptableObject call. With this function we're telling Silverlight to make this class accessible via scripts by the name "SilverlightApp". Now whenever I want to use this object in Javascript, I'll reference it by the name "SilverlightApp". We'll see how this works later. Now that everything is setup, let's look at some C# code to fire our newly created events.

void ButtonA(object sender, MouseEventArgs e){ if (ButtonAClicked != null) ButtonAClicked(this, e);}void ButtonB(object sender, MouseEventArgs e){ if (ButtonBClicked != null) ButtonBClicked(this, e);}void ButtonC(object sender, MouseEventArgs e){ if (ButtonCClicked != null) ButtonCClicked(this, e);}

In my XAML code I hooked up a MouseLeftButtonUp event to each of my buttons. Now when a button is clicked, one of these functions will be called. As you can see, firing the events is no different than a C# application. You should always make sure to check that an event is not null before firing it - otherwise things tend to crash. An event will be null if nothing has attached to it. That's all the code required on the Silverlight side to call Javascript functions. Now let's look at how to make Javascript listen for these events. The first thing we need to do is attach Javascript functions to each event. We'll do this as soon as the Silverlight application is done loading. So now you're probably wondering, how do we know when the Silverlight is done loading? There's an event we can listen for that is called as soon as it's finished. In order to get this event we need to modify the Javascript that Visual Studio generated as part of the test code. In my solution, the .js file is named TestPage.html.js. It might be different for you depending on how you set it up.

// JScript source code//
contains calls to silverlight.js, example below loads Page.xamlfunction createSilverlight(){ Silverlight.createObjectEx({ source: "Page.xaml", parentElement: document.getElementById( "SilverlightControlHost"), id: "SilverlightControl", properties: { width: "100%", height: "100%", version: "1.1", enableHtmlAccess: "true" }, events: {onLoad: OnLoaded} }); // Give the keyboard focus to the Silverlight // control by default document.body.onload = function() { var silverlightControl = document.getElementById('SilverlightControl'); if (silverlightControl) silverlightControl.focus(); }}

This should look very similar to what Visual Studio has created for you. The addition we have to make is in the events: {} section. We need to add an event for onLoad. With this addition, we're telling Silverlight to call the Javascript function OnLoaded as soon as it's finished loading. The OnLoaded function is where we're going to be attaching Javascript functions to our Silverlight events. So let's see how that's done.

function OnLoaded(sender, args)
sender.Content.SilverlightApp.ButtonAClicked = ButtonAClicked; sender.Content.SilverlightApp.ButtonBClicked = ButtonBClicked; sender.Content.SilverlightApp.ButtonCClicked = ButtonCClicked;}function ButtonAClicked(){ //The Silverlight A button has been clicked
function ButtonBClicked(){ //The Silverlight B button has been clicked }function ButtonCClicked(){
//The Silverlight C button has been clicked

The OnLoaded event is automatically passed in the Silverlight object and some event arguments. Here's where we use the "SilverlightApp" name we created above. With those assignments, we're telling Silverlight to execute a Javascript function whenever one of those events is fired. So now, whenever the event ButtonAClicked is fired from the Silverlight Application, the Javascript function ButtonAClicked will be executed. That's it for calling Javascript functions from Silverlight. Now let's look at how to call Silverlight functions from Javascript. This process is much easier than calling Javascript from Silverlight. The first thing we need is a C# function we want called.
Let's add one to our Silverlight code behind.

Scriptable]public void HTMLButtonAClicked(){ //The HTML A button has been clicked}

There nothing special about this function except for the [Scriptable] attribute which makes it accessible by our Javascript code. All that's left is to call this function from the Javascript code.

var slApp = document.getElementById('SilverlightControl');slApp.Content.SilverlightApp.HTMLButtonAClicked();

As you can see, this is much easier than the other way around. The first thing we need to do is get the Silverlight object. You're probably wondering where the "SilverlightControl" id came from which is passed into getElementById. This is set back in the .js file that Visual Studio created for you. All that's left to do is access the class we named "SilverlightApp" and call the HTMLButtonAClicked function. Once that's done, the function we wrote in the C# code behind will be executed. I hoped you enjoyed this tutorial on Silverlight and Javascript interaction. Post a comment if you have any questions.