共用方式為


Walkthrough: Creating a Silverlight Clock by Using Expression Blend or Visual Studio

Microsoft Silverlight will reach end of support after October 2021. Learn more.

In Silverlight, you create your user interface (UI) elements using Extensible Markup Language (XAML). To write XAML, you can use a visual design tool, such as Expression Blend, or you can use Visual Studio This walkthrough shows you how to create a simple clock in Silverlight by using Expression Blend and Visual Studio. The following illustration shows the clock that you will create.

Clock sample

If you use Expression Blend, you will create the graphics visually in the designer. If you use Visual Studio, you will create the graphics by typing in the XAML. Once you have created the graphics that make up the appearance of the clock, you will add animations and logic to make the clock work.

Run this sample

Download this sample

Prerequisites

You need the following components to complete this walkthrough (available from the Silverlight download site):

  • Expression Blend 4 (optional).

  • Visual Studio 2010.

  • Silverlight 4 or later.

Creating the Clock by Using Expression Blend

Expression Blend will speed up the creation of your Silverlight application, especially when you are designing graphics and layout. In this section, you will create the clock by using Expression Blend.

The clock consists of the graphical elements shown in the following illustration.

Graphical elements of the clock

These graphics are created with simple elements arranged on a Grid. All the circular graphics, including the clock face, outer rim, bevel, and shadow, are created with Ellipse elements, and the clock hands are created with Rectangle elements.

To create a new Silverlight Application project in Expression Blend

  1. Start Expression Blend. If the startup form appears, click Close.

  2. On the File menu, click New Project.

    The New Project dialog box is displayed.

  3. In the Project types pane, select Silverlight.

  4. In the list of projects, select Silverlight Application.

    New Project Dialog Box

  5. In the Name box, type SilverlightClock.

  6. In the Language list, select Visual Basic or Visual C#.

  7. In the Version list, select 4.0.

  8. Click OK to create the project.

    Next, you will set the size of the artboard.

  9. In the Objects and Timeline panel, select [UserControl].

    New Project Objects And Timeline

  10. In the Properties panel, under Layout, set the Width and Height to 400.

    New Project Layout

    The size of the artboard is changed.

    At this point you have an empty project. If you press F5 to run the application, you will only see a blank Web page.

The graphics of the clock consists of layers of overlapping shapes, which create the overall appearance of a clock. To create the clock, you will build the clock up one layer at a time, starting with the lowest layer, which is the shadow of the clock.

To create the shadow of the clock

  1. In the Tools panel, right-click the Rectangle tool and click Ellipse.

    Shadow Ellipsis Tool

  2. On the artboard, draw an ellipse approximately 330 pixels wide and high. When you are drawing, press the SHIFT key to keep the width and height equal.

  3. If you need to reposition the ellipse, in the Tools panel, click the Selection tool and reposition the ellipse.

    Shadow Selection Tool

    Next, you will change the ellipse properties.

  4. In the Properties panel, in the Name box, set the name of the ellipse to shadowEllipse.

    Shadow Properties Name Ellipsis

  5. In the Properties panel, under Brushes, click Fill and then click Solid color brush.

  6. In the color Editor, set the color to black.

    Shadow Properties Brushes Color

  7. Under Appearance, set Opacity to 30%.

    Shadow Properties Appearance Opacity

    The ellipse now has a fill of semi-transparent black, which will provide the shadow effect.

  8. On the File menu, click Save All.

Next, you will create the outer rim of the clock. Since the outer rim is the same size as the shadow ellipse, you can create it by simply making a copy of the shadow ellipse.

To create the outer rim of the clock

  1. In the Tools panel, click the Selection tool.

  2. On the artboard, click the shadow ellipse to make sure that it is selected.

  3. On the Edit menu, select Copy or press CTRL+C.

  4. On the Edit menu, select Paste or press CTRL+V.

    A new ellipse named shadowEllipse_Copy appears exactly on top of the shadow ellipse.

  5. In the Properties panel, set the name to outerRimEllipse.

    Next, you will fill outerRimEllipse with a simple gradient. Creating a gradient in Expression Blend consists of several steps.

  6. In the Objects and Timeline panel, make sure that outerRimEllipse is selected.

    Outer Rim Objects And Timeline

  7. In the Properties panel, under Appearance, set the Opacity to 100%.

  8. In the Properties panel, under Brushes, click Fill and then click Gradient brush.

  9. In the gradient bar of the color Editor, click the left gradient stop and set its color to #FFE4E5F4.

  10. Click the right gradient stop and set its color to #FFC0C0C0.

    Outer Rim Properties Brushes

    Next, you will change the direction of the linear gradient so that it is going from the upper left to the lower right (instead of going from left to right over the ellipse).

  11. In the Tools panel, click the Gradient Tool.

    Outer Rim Gradient Tool

    A vertical arrow appears on the outerRimEllipse.

  12. Move your mouse pointer near the arrow head or arrow tail until your pointer turns into a rotate icon.

  13. Rotate the arrow to set the direction of the linear gradient from the upper left to the lower right.

  14. In the Properties panel, under Brushes, drag the right gradient stop left to concentrate the gradient on the left side.

    The gradient direction is shown in the following illustration.

    Outer Rim Gradient

  15. In the Tools panel, click the Selection tool.

  16. Drag outerRimEllipse slightly to the upper left to see the shadow.

    You will notice a sliver of shadowEllipse visible in the lower right, which creates a shadow effect.

    Outer Rim Artboard Shadow

Next, you will create the bevel of the clock. The ellipse you use to make the bevel will be similar to outerRimEllipse, only a little smaller.

To create the bevel of the clock

  1. Select outerRimEllipse.

  2. Create a copy of outerRimEllipse and paste it.

  3. In the Properties panel, set the name of the outerRimEllipse copy to bevelEllipse.

  4. In the Properties panel, under Layout, set the Width and Height to 290.

    Bevel Properties Layout

    Next, you will fill bevelEllipse with a linear gradient. Because bevelEllipse is a copy of outerRimEllipse, it will already have a gradient applied to it.

  5. In the Properties panel, under Brushes, click the left gradient stop and set its color to #FF2F2F32.

  6. Click the right gradient stop and set its color to #FFE4E5F4.

  7. Drag the right gradient stop to the right until it is 100%.

    This gradient runs in the same direction as the gradient applied to outerRimEllipse. However, the bevelEllipse gradient goes from dark in the upper-left to light in the lower-right, which is the opposite of the gradient applied to outerRimEllipse. The following illustration shows the gradient.

    Bevel Gradient

Next, you will create the face of the clock. The ellipse you use to make the face will be similar to bevelEllipse, only a little smaller.

To create the face of the clock

  1. Select bevelEllipse.

  2. Create a copy of bevelEllipse and paste it.

  3. In the Properties panel, set the name of the bevelEllipse copy to faceEllipse.

  4. In the Properties panel, under Layout, set the Width and Height to 270.

  5. In the Properties panel, under Brushes, click Fill, click Solid color brush, and then set the color to black.

    Notice that the addition of this ellipse makes the bevel visible.

    Face

Next, you will create the center ellipse of the clock.

To create the center ellipse of the clock

  1. In the Tools panel, click the Ellipse tool.

  2. Draw a small ellipse in the center of the clock face. Do not worry about trying to position it exactly.

  3. In the Properties panel, set the name to centerEllipse.

  4. In the Properties panel, under Brushes, select Stroke, select Solid color brush, and then set the color to green.

    Center Ellipse Properties Brushes

  5. In the Properties panel, under Appearance, set the StrokeThickness to 8.

    Center Ellipse Properties Appearance

  6. In the Properties panel, under Layout, Set the Width and Height to 30.

    Next, you will position the center ellipse in the middle of the clock face.

  7. In the Objects and Timeline panel, select centerEllipse.

  8. While pressing the CTRL key, select faceEllipse to select both centerEllipse and faceEllipse.

    Center Ellipse Objects And Timeline

  9. On the Object menu, click Align, and then click Horizontal Centers.

    centerEllipse is aligned horizontally.

  10. On the Object menu, click Align, and then click Vertical Centers.

    centerEllipse is aligned vertically.

    Center Ellipse Align

Next, you will create the hands of the clock.

To create the hands of the clock

  1. In the Tools panel, right-click the Ellipse tool and click the Rectangle tool.

    Hands Rectangle Tool

  2. On the clock face, draw a tall thin rectangle that represents the 12 o’clock position.

  3. In the Properties panel, set the name to secondHand.

  4. In the Properties panel, under Brushes, click Fill, click Solid color brush, and then set the color to red.

  5. In the Properties panel, under Layout, set the Width to 5 and Height to 80.

  6. In the Objects and Timeline panel, select secondHand, press the CTRL key, and then select faceEllipse.

  7. On the Object menu, click Align and then click Horizontal Centers.

  8. In the Tools panel, click the Selection tool.

  9. In the Objects and Timeline panel, click secondHand to just select the secondHand.

  10. In the lower-left corner of the artboard, click the Zoom arrow to zoom in on secondHand.

    Hands Zoom

    In the next step you will change the center point of the rectangle to the center of the clock face. Later, you will animate the clock hands around the center of the clock.

  11. Drag the center point of the secondHand rectangle to the center of the clock face.

    Hands Center Point

    If necessary, you can change the center point in the Properties panel. Expand Transform, click the Center Point tab, and the change the X and Y values.

    Hands Properties Transform Center Point

  12. Create a second rectangle that represents the minute hand with the following properties.

    • Name = minuteHand

    • Fill, Solid color brush, green

    • Width = 9, Height = 80

    • Align horizontal centers

    • Center point set to center of clock face

  13. Create a third rectangle that represents the hour hand with the following properties.

    • Name = hourHand

    • Fill, Solid color brush, green

    • Width = 11, Height = 60

    • Align horizontal centers

    • Center point set to center of clock face

    When you are finished, your clock hands will be overlapping each other.

    Hands All

    In the next section, you will add animations that rotate the hands around the clock. This will be done by animating the Angle property of the RotateTransform element that is applied to the clock hand. Because the animation will have to target the correct RotateTransform, you will have to name the RotateTransform elements applied to each of the clock hands. There is not a way to change the name of the RotateTransform elements in the Expression Blend UI, so you will have to do this in XAML.

  14. In the upper-right corner of the artboard, click the XAML or Split view tab.

    Hands View Tabs

    You can now see the XAML markup for all of the objects that you have created in the designer. The clock hands are created with Rectangle elements.

  15. Find the secondhand rectangle in the XAML.

  16. Modify the secondHand rectangle by adding a Rectangle.RenderTransform element and a RotateTransform named secondHandTransform as shown in the following XAML.

      <!-- Second Hand -->
    <Rectangle x:Name="secondHand" ...>
        <Rectangle.RenderTransform>
            <RotateTransform x:Name="secondHandTransform"/>
        </Rectangle.RenderTransform>
    </Rectangle>
    
  17. Modify the minuteHand rectangle and name the RotateTransformminuteHandTransform.

      <!-- Minute Hand -->
    <Rectangle x:Name="minuteHand" ...>
        <Rectangle.RenderTransform>
            <RotateTransform x:Name="minuteHandTransform"/>
        </Rectangle.RenderTransform>
    </Rectangle>
    
  18. Modify the hourHand rectangle and name the RotateTransformhourHandTransform.

      <!-- Hour Hand -->
    <Rectangle x:Name="hourHand" ...>
        <Rectangle.RenderTransform>
            <RotateTransform x:Name="hourHandTransform"/>
        </Rectangle.RenderTransform>
    </Rectangle>
    
  19. In the upper-right corner, click the Design view tab to display design view.

  20. Save the project.

At this point, you have created all the graphics for the clock. Next, you will apply animations to the rotation transforms of the clock hands. These rotation animations will make the clock hands rotate around the center of the clock (as you would expect clock hands to do). By specifying the timing of the animations, you can make the hands rotate around the clock in sync with the current time on the computer.

To add the clock hand animations

  1. Display the Projects panel.

  2. Make sure that MainPage.xaml is selected.

    Animations Projects

  3. Click the XAML or Split view tab to display the XAML.

  4. After the UserControl start element, add the following markup to add the clock hand animations.

    <UserControl.Resources>
        <Storyboard x:Name="clockStoryboard">
            <!-- This animation targets the hour hand transform -->
            <DoubleAnimation x:Name="hourAnimation"
              Storyboard.TargetName="hourHandTransform"
              Storyboard.TargetProperty="Angle"
              Duration="12:0:0" RepeatBehavior="Forever" To="360"/>
    
            <!-- This animation targets the minute hand transform -->
            <DoubleAnimation x:Name="minuteAnimation"
              Storyboard.TargetName="minuteHandTransform" 
              Storyboard.TargetProperty="Angle"
              Duration="1:0:0" RepeatBehavior="Forever" To="360" />
    
            <!-- This animation targets the second hand transform  -->
            <DoubleAnimation x:Name="secondAnimation"
              Storyboard.TargetName="secondHandTransform" 
              Storyboard.TargetProperty="Angle"
              Duration="0:1:0" RepeatBehavior="Forever" To="360" />
        </Storyboard>
    </UserControl.Resources>
    

    This markup defines a Storyboard that contains the animations that animate the hands of the clock. All of these animations target the Angle property of the respective clock hand transform. The Duration property of each animation is set depending on the desired speed of the animation. For example, for the hour hand transform, the duration of the animation is set for 12 hours, which is the time it takes the hour hand to go completely around the clock. The RepeatBehavior of all of the animations are set to "Forever". Therefore, when the animation completes (the hand goes around the clock), it starts over again and repeats indefinitely.

    To start the Storyboard, you will use the Loaded event to call the Begin method on the Storyboard.

  5. Find the Grid element and add the following Loaded attribute.

    This specifies to call the SetAndStartClock event handler when the application is loaded.

    <Grid x:Name="LayoutRoot" Background="White" Loaded="SetAndStartClock">
    

    Next, you will add the event handler.

  6. In the Projects panel, expand the MainPage.xaml node and double-click the code-behind file MainPage.xaml.vb or MainPage.xaml.cs.

    The code-behind file opens in the code editor.

  7. In the MainPage class, add the following SetAndStartClock method, which starts the Storyboard.

    Private Sub SetAndStartClock(ByVal sender As Object, ByVal e As EventArgs)
    
        ' Start the storyboard.
        clockStoryboard.Begin()
    End Sub
    
    private void SetAndStartClock(object sender, EventArgs e)
    {
        // Start the storyboard.
        clockStoryboard.Begin();
    }
    
  8. Save the project.

  9. Click the Project menu and then click Run Project to build and run the application. (You can also press F5 to run the application.)

    Your Web browser opens and the clock starts running. Notice that the second hand is moving around the clock. The other hands are also moving, but they are moving too slowly to be perceptible.

Although the clock hands are moving at the rate they are supposed to, the clock is not set to the current time. To set the clock, you will need to add some logic.

To set the clock to the current time

  1. Close the browser and open MainPage.xaml.vb or MainPage.xaml.cs.

  2. Replace the SetAndStartClock procedure with the following code.

    This code sets the clock hands to the current time.

    Private Sub SetAndStartClock(ByVal sender As Object, ByVal e As EventArgs)
    
        ' The current date and time.
        Dim currentDate As Date = DateTime.Now
    
        ' Find the appropriate angle (in degrees) for the hour hand
        ' based on the current time.
        Dim hourangle As Double = (((CType(currentDate.Hour, Single) / 12) * 360) + (currentDate.Minute / 2))
    
        ' The same as for the minute angle.
        Dim minangle As Double = ((CType(currentDate.Minute, Single) / 60) * 360)
    
        ' The same for the second angle.
        Dim secangle As Double = ((CType(currentDate.Second, Single) / 60) * 360)
    
        ' Set the beginning of the animation (From property) to the angle 
        ' corresponging to the current time.
        hourAnimation.From = hourangle
    
        ' Set the end of the animation (To property)to the angle 
        ' corresponding to the current time PLUS 360 degrees. Thus, the
        ' animation will end after the clock hand moves around the clock 
        ' once. Note: The RepeatBehavior property of the animation is set
        ' to "Forever" so the animation will begin again as soon as it completes.
        hourAnimation.To = (hourangle + 360)
    
        ' Same as with the hour animation.
        minuteAnimation.From = minangle
        minuteAnimation.To = (minangle + 360)
    
        ' Same as with the hour animation.
        secondAnimation.From = secangle
        secondAnimation.To = (secangle + 360)
    
        ' Start the storyboard.
        clockStoryboard.Begin()
    
    End Sub
    
    private void SetAndStartClock(object sender, EventArgs e)
    {
        // The current date and time.
        System.DateTime currentDate = DateTime.Now;
    
        // Find the appropriate angle (in degrees) for the hour hand
        // based on the current time.
        double hourangle = (((float)currentDate.Hour) / 12) * 360 + currentDate.Minute / 2;
    
    
        // The same as for the minute angle.
        double minangle = (((float)currentDate.Minute) / 60) * 360;
    
        // The same for the second angle.
        double secangle = (((float)currentDate.Second) / 60) * 360;
    
        // Set the beginning of the animation (From property) to the angle 
        // corresponging to the current time.
        hourAnimation.From = hourangle;
    
        // Set the end of the animation (To property)to the angle 
        // corresponding to the current time PLUS 360 degrees. Thus, the
        // animation will end after the clock hand moves around the clock 
        // once. Note: The RepeatBehavior property of the animation is set
        // to "Forever" so the animation will begin again as soon as it completes.
        hourAnimation.To = hourangle + 360;
    
        // Same as with the hour animation.
        minuteAnimation.From = minangle;
        minuteAnimation.To = minangle + 360;
    
        // Same as with the hour animation.
        secondAnimation.From = secangle;
        secondAnimation.To = secangle + 360;
    
        // Start the storyboard.
        clockStoryboard.Begin();
    }
    
  3. Run the application.

    The clock hands should now be set to the current time.

Creating the Clock by Using Visual Studio

Instead of using Expression Blend, you can create the graphics for the clock directly in XAML. This section of the walkthrough shows you how to create the same clock by using Visual Studio.

The clock consists of the graphical elements shown in the following illustration.

Graphical elements of the clock

These graphics are created with simple elements arranged on a Grid. All the circular graphics, including the clock face, outer rim, bevel, and shadow, are created with Ellipse elements, and the clock hands are created with Rectangle elements.

To create a new Silverlight Application project in Visual Studio

  1. Start Visual Studio.

  2. Create a new Silverlight Application project named SilverlightClock in Visual Basic or Visual C#.

  3. In the New Silverlight Application dialog box, clear the Host the Silverlight application in a new Web site check box and in the Silverlight Version list, select Silverlight 4. For more information, see How to: Create a New Silverlight Project.

The graphics of the clock are composed of layers of overlapping shapes, which create the overall appearance of a clock. To create the clock, you will build the clock up one layer at a time, starting with the lowest layer, which is the shadow of the clock.

To create the shadow of the clock

  1. Open MainPage.xaml.

  2. Replace the existing XAML with the following XAML to create the shadow of the clock.

    <UserControl x:Class="SilverlightClock.MainPage"
        xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="https://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="https://schemas.openxmlformats.org/markup-compatibility/2006"
        mc:Ignorable="d"
        Height="400" Width="400">
    
        <Grid x:Name="LayoutRoot">
            <!-- Shadow -->
            <Ellipse Fill="#FF000000" Height="330" Margin="42,42,28,28" 
              Opacity="0.3" Width="330" />
    
        </Grid>
    </UserControl>
    

    The following illustration shows the results.

    Shadow Ellipsis VS

    Notice that the fill is set to black and the opacity is set to 0.3 (30%). This makes the fill of the ellipse semi-transparent, like a shadow. The width, height, and margin are arbitrary. These properties simply specify the size and position of the circle within the Grid.

    NoteNote:

    Most XAML markup in Silverlight applications is not affected by the procedural language you use (for example, Visual Basic, C#, or JavaScript).

Next, you will create the outer rim of the clock.

To create the outer rim of the clock

  • In MainPage.xaml, after the shadow ellipse, add the following XAML to create the outer rim of the clock.

    <!-- Outer Rim -->
    <Ellipse Height="330" Margin="35,35,35,35" Stroke="#FF000000" Width="330" >
        <Ellipse.Fill>
            <LinearGradientBrush EndPoint="0.84,0.87" StartPoint="0.164,0.129">
                <GradientStop Color="#FFE4E5F4" />
                <GradientStop Color="#FFC0C0C0" Offset="0.254"/>
            </LinearGradientBrush>
        </Ellipse.Fill>
    </Ellipse>
    

    The following illustration shows the results.

    Outer Rim VS

    The shadow ellipse is positioned slightly to the lower right, allowing only a sliver of that ellipse to be visible from underneath. This results in a shadow effect. Also, notice that a linear gradient is applied to the outer rim ellipse. This linear gradient is positioned to create the appearance of light coming from the upper left of the ellipse.

Next, you will add the bevel of the clock.

To create the bevel of the clock

  • In MainPage.xaml, after the outer rim ellipse, add the following XAML to create the bevel of the clock.

    <!-- Bevel -->
    <Ellipse Height="290" Margin="55,55,55,55" Width="290" Stroke="#FF000000">
        <Ellipse.Fill>
            <LinearGradientBrush EndPoint="0.84,0.87" StartPoint="0.164,0.129">
                <GradientStop Color="#FF2F2F32"/>
                <GradientStop Color="#FFE4E5F4" Offset="0.987"/>
            </LinearGradientBrush>
        </Ellipse.Fill>
    </Ellipse>
    

    The following illustration shows the results.

    Bevel VS

    This ellipse is slightly smaller than the ellipse used to create the outer rim, and it is positioned directly over the outer rim ellipse. In addition, this ellipse also has a linear gradient applied to it, but this gradient goes from dark in the upper left to light in the lower right.

Next, you will create the face of the clock.

To create the face of the clock

  • In MainPage.xaml, after the bevel ellipse, add the following XAML to create the face of the clock.

    <!-- Face -->
    <Ellipse Fill="#FF000000" Height="270" Margin="65,65,65,65" 
      Stroke="#FF000000" Width="270" />
    

    The clock face is simply a black filled ellipse, slightly smaller than the bevel ellipse, positioned directly over the other ellipses. Also, notice that addition of this ellipse makes the bevel visible.

    Face VS

Next, you will create the center ellipse and hands of the clock.

To create the center ellipse and hands of the clock

  • In MainPage.xaml, after the face ellipse, add the following XAML to create the center ellipse and hands of the clock.

    <!-- Center -->
    <Ellipse Fill="#FF000000" Height="30" Margin="185,185,185,185" 
      Stroke="#FF008000" StrokeThickness="8" VerticalAlignment="Top" 
      Width="30" />
    
    <!-- Second Hand -->
    <Rectangle x:Name="secondHand" Fill="#FFFF0000" Height="80" 
      Margin="198,90,197,0"  RenderTransformOrigin="0.45,1.34" 
      Stroke="#FF000000" VerticalAlignment="Top" Width="5" >
        <Rectangle.RenderTransform>
            <RotateTransform x:Name="secondHandTransform"/>
        </Rectangle.RenderTransform>
    </Rectangle>
    
    <!-- Minute Hand -->
    <Rectangle x:Name="minuteHand" Fill="#FF008000" Height="80" 
      Margin="196,90,195,0" RenderTransformOrigin="0.45,1.34" 
      Stroke="#FF008000" VerticalAlignment="Top" Width="9" >
        <Rectangle.RenderTransform>
            <RotateTransform x:Name="minuteHandTransform"/>
        </Rectangle.RenderTransform>
    </Rectangle>
    
    <!-- Hour Hand -->
    <Rectangle x:Name="hourHand" Fill="#FF008000" Height="60" 
      Margin="195,110,194,0" RenderTransformOrigin="0.45,1.45" 
      Stroke="#FF008000" VerticalAlignment="Top" Width="11" >
        <Rectangle.RenderTransform>
            <RotateTransform x:Name="hourHandTransform"/>
        </Rectangle.RenderTransform>
    </Rectangle>
    

    The following illustration shows the results. The second hand, minute hand, and hour hand are overlapping in this illustration.

    Center Hands VS

    In the previous code, the minute hand, hour hand, and second hand share the same values for properties that determine positioning (for example, Margin). However, the hands differ from one another in size and/or color (for example, the hour hand is thickest because it has the largest StrokeThickness value).

    Notice that all of the hands have a RotateTransform applied to them. This transform enables you to rotate the angle of the hand. In the next section, you will animate the angle of this transform, which will make the clock hands move to show the time. Each of the RotateTransform elements have a name (for example, x:Name="hourHandTransform"). This is done so you can associate an animation with the transform. Also, notice that all of the hands have a RenderTransformOrigin value. This property is used to specify the point on the canvas that all transforms are made relative to. Since you are going to rotate the hands around the center of the clock, the value of the RenderTransform property for all hands is given as the center of the clock face.

At this point, you have created all the graphics for the clock. Next, you will apply animations to the rotation transforms of the clock hands. These rotation animations will make the clock hands rotate around the center of the clock (as you would expect clock hands to do). By specifying the timing of the animations, you can make the hands rotate around the clock in sync with the current time on the computer.

To add the clock hand animations

  1. In MainPage.xaml, after the UserControl start element, add the following markup to add the clock hand animations.

    <UserControl.Resources>
        <Storyboard x:Name="clockStoryboard">
           <!--This animation targets the hour hand transform-->
           <DoubleAnimation x:Name="hourAnimation" 
              Storyboard.TargetName="hourHandTransform" 
              Storyboard.TargetProperty="Angle" 
              Duration="12:0:0" RepeatBehavior="Forever" To="360" />
    
            <!--This animation targets the minute hand transform-->
            <DoubleAnimation x:Name="minuteAnimation" 
              Storyboard.TargetName="minuteHandTransform" 
              Storyboard.TargetProperty="Angle" 
              Duration="1:0:0" RepeatBehavior="Forever" To="360" />
    
            <!--This animation targets the minute hand transform-->
            <DoubleAnimation x:Name="secondAnimation" 
              Storyboard.TargetName="secondHandTransform" 
              Storyboard.TargetProperty="Angle" 
              Duration="0:1:0" RepeatBehavior="Forever" To="360" />
        </Storyboard>
    </UserControl.Resources>
    

    This markup defines a Storyboard that contains the animations that animate the hands of the clock. All of these animations in the Storyboard target the Angle property of the respective clock hand transform. The Duration property of each animation is set depending on the desired speed of the animation. For example, for the hour hand transform, the duration of the animation is set for 12 hours, which is the time it takes the hour hand to go completely around the clock. The RepeatBehavior of all of the animations are set to "Forever". Therefore, when the animation completes (the hand goes around the clock), it starts over again and repeats indefinitely.

    To start the Storyboard, use the Loaded event to call the Begin method on the Storyboard.

  2. In the Grid element, add the following Loaded attribute.

    This specifies to call the SetAndStartClock event handler when the application is loaded.

    <Grid x:Name="LayoutRoot" Loaded="SetAndStartClock">
    

    Next, you will add the event handler.

  3. In Solution Explorer, expand MainPage.xaml and open the code-behind MainPage.xaml.vb or MainPage.xaml.cs.

  4. In the MainPage class, add the following SetAndStartClock method, which starts the Storyboard.

    Private Sub SetAndStartClock(ByVal sender As Object, ByVal e As EventArgs)
    
        ' Start the storyboard.
        clockStoryboard.Begin()
    End Sub
    
    private void SetAndStartClock(object sender, EventArgs e)
    {
        // Start the storyboard.
        clockStoryboard.Begin();
    }
    
  5. Save the project.

  6. On the Debug menu, click Start Debugging or press F5 to run the application.

    Your Web browser opens and the clock starts running. Notice that the second hand is moving around the clock. The other hands are also moving, but they are moving too slowly to be perceptible.

Although the clock hands are moving at the rate they are supposed to, the clock is not set to the current time. To set the clock, you will need to add some logic.

To set the clock to the current time

  1. Close the browser and open MainPage.xaml.vb or MainPage.xaml.cs.

  2. Replace the SetAndStartClock procedure with the following code.

    This code sets the clock hands to the current time.

    Private Sub SetAndStartClock(ByVal sender As Object, ByVal e As EventArgs)
    
        ' The current date and time.
        Dim currentDate As Date = DateTime.Now
    
        ' Find the appropriate angle (in degrees) for the hour hand
        ' based on the current time.
        Dim hourangle As Double = (((CType(currentDate.Hour, Single) / 12) * 360) + (currentDate.Minute / 2))
    
        ' The same as for the minute angle.
        Dim minangle As Double = ((CType(currentDate.Minute, Single) / 60) * 360)
    
        ' The same for the second angle.
        Dim secangle As Double = ((CType(currentDate.Second, Single) / 60) * 360)
    
        ' Set the beginning of the animation (From property) to the angle 
        ' corresponging to the current time.
        hourAnimation.From = hourangle
    
        ' Set the end of the animation (To property)to the angle 
        ' corresponding to the current time PLUS 360 degrees. Thus, the
        ' animation will end after the clock hand moves around the clock 
        ' once. Note: The RepeatBehavior property of the animation is set
        ' to "Forever" so the animation will begin again as soon as it completes.
        hourAnimation.To = (hourangle + 360)
    
        ' Same as with the hour animation.
        minuteAnimation.From = minangle
        minuteAnimation.To = (minangle + 360)
    
        ' Same as with the hour animation.
        secondAnimation.From = secangle
        secondAnimation.To = (secangle + 360)
    
        ' Start the storyboard.
        clockStoryboard.Begin()
    
    End Sub
    
    private void SetAndStartClock(object sender, EventArgs e)
    {
        // The current date and time.
        System.DateTime currentDate = DateTime.Now;
    
        // Find the appropriate angle (in degrees) for the hour hand
        // based on the current time.
        double hourangle = (((float)currentDate.Hour) / 12) * 360 + currentDate.Minute / 2;
    
    
        // The same as for the minute angle.
        double minangle = (((float)currentDate.Minute) / 60) * 360;
    
        // The same for the second angle.
        double secangle = (((float)currentDate.Second) / 60) * 360;
    
        // Set the beginning of the animation (From property) to the angle 
        // corresponging to the current time.
        hourAnimation.From = hourangle;
    
        // Set the end of the animation (To property)to the angle 
        // corresponding to the current time PLUS 360 degrees. Thus, the
        // animation will end after the clock hand moves around the clock 
        // once. Note: The RepeatBehavior property of the animation is set
        // to "Forever" so the animation will begin again as soon as it completes.
        hourAnimation.To = hourangle + 360;
    
        // Same as with the hour animation.
        minuteAnimation.From = minangle;
        minuteAnimation.To = minangle + 360;
    
        // Same as with the hour animation.
        secondAnimation.From = secangle;
        secondAnimation.To = secangle + 360;
    
        // Start the storyboard.
        clockStoryboard.Begin();
    }
    
  3. Run the application.

    The clock hands should now be set to the current time.

Conclusion

In this walkthrough, you have learned how to do the following in Silverlight:

  • Design overlapping vector graphics that create the appearance of a real-life clock.

  • Use gradients to create shadowing and depth.

  • Use animations to add functionality to the clock.

  • Use code to set the clock to the correct time.

  • Learn how to use Expression Blend and Visual Studio to create Silverlight applications.