Silverlight
Walkthrough: Creating Your First Silverlight Application

[Note: This topic is pre-release documentation and is subject to change in future releases. Blank topics are included as placeholders.]

This walkthrough shows you how to get started programming in Silverlight and Visual Studio by creating a simple application. This walkthrough demonstrates the following concepts.

  • Creating a dynamic layout using the Grid and StackPanel controls.

  • Adding core controls and Silverlight SDK controls.

  • Adding an event handler.

  • Adding code logic.

To view a running sample of this application, click the following link.

Run this sample

Prerequisites

You need the following components to complete this walkthrough:

  • Silverlight version 2.

  • Silverlight Tools for Visual Studio 2008.

  • Silverlight SDK (part of the Silverlight Tools for Visual Studio 2008).

  • Visual Studio 2008 SP1.

All of the Silverlight software is available from the Silverlight download site.

Creating a Silverlight Project

The first step is to create a Silverlight project.

To create a Silverlight project

  1. Create a new Silverlight Application project named HelloSilverlight in Visual Basic or Visual C#. Select the Automatically generate a test page to host Silverlight at build time option. For more information, see How to: Create a New Silverlight Project.

  2. Open Solution Explorer and notice that there are App.xaml and a Page.xaml files.

    App.xaml allows you to specify resources and code that applies to the entire application. Page.xaml defines a page, similar to a page in a Web site.

  3. In Solution Explorer, expand the Page.xaml node.

    Page.xaml.vb or Page.xaml.cs is the code-behind file that you write your managed code. This model is similar to one used in ASP.NET.

  4. If Page.xaml is not already open, double-click it in Solution Explorer.

    In the center of Visual Studio, you should see a white rectangular area with a dark background. This area is called the Silverlight Preview window. The Preview window is read-only and displays a rendering of the XAML markup.

    Below the Preview window is XAML view. XAML view is where you add your XAML to create your layout and designs. As you type markup and add Toolbox controls to XAML view, the results are rendered in the Preview window. To help you work in XAML view, IntelliSense is displayed and wavy lines appear to indicate mistakes. For more information about the designer features, see Silverlight Tools for Visual Studio 2008 Designer Support.

    New Silverlight project in Visual Studio 2008
Defining the Grid Layout

By default, Silverlight projects include a Grid. A Grid allows you to create a table-type layout similar to a table in HTML. This section describes how to create a Grid layout. In a later section, you will learn how to make the layout dynamic.

To define the Grid layout

  1. In XAML view, locate the Grid element.

  2. In the Grid start tag, change the Background color by replacing "White" with another color.

    As you type, you should see an IntelliSense window with a list of colors to choose. When you specify a color, the Preview window updates with the new color.

    IntelliSense window in XAML view
  3. In the Grid start tag, add the ShowGridLines property and set it to True as shown in the following XAML.

    <Grid x:Name="LayoutRoot" Background="Beige" ShowGridLines="True">
    

    This property specifies to add dotted lines to identify rows and columns in the Grid. This is a useful debugging feature when you are creating Grid layouts.

  4. Within the Grid element, add the following XAML to define three rows and two columns.

    <Grid x:Name="LayoutRoot" Background="Beige" ShowGridLines="True">
        <Grid.RowDefinitions>
            <RowDefinition Height="40"/>
            <RowDefinition Height="220"/>
            <RowDefinition Height="40"/>
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="75" />
            <ColumnDefinition Width="325"/>
        </Grid.ColumnDefinitions>
    </Grid>
    

    In the Preview window, you see dotted lines identifying the rows and columns.

  5. Press F5 or click the Start Debugging toolbar button to run the application.

    Your browser opens and you see a rectangle in the upper-left corner of the window with your defined Grid, as shown in the following illustration.

    Grid layout in browser
  6. Close your browser to return to Visual Studio.

Adding Controls

Silverlight has several controls to help you display data and get input from the user. This section describes how to add TextBlock, TextBox, StackPanel, Calendar, and Button controls to your Grid layout.

To add controls

  1. Open the Toolbox window if it is not already open and expand the Silverlight XAML Controls tab.

    Silverlight XAML controls in the Toolbox
  2. From the Toolbox, drag a TextBlock control to just after the </Grid.ColumnDefinitions> end tag in XAML view.

    <TextBlock></TextBlock> markup is added to XAML view.

  3. In the TextBlock start tag, add the following Text property.

    <TextBlock Text="Name:"></TextBlock>
    
  4. After the Name TextBlock, add another TextBlock with Text="Date:".

  5. After the Date TextBlock, add another TextBlock with Text="Message:".

    In the Preview window, you can see that the TextBlock elements overlap each other in the first cell. To position the TextBlock elements in Grid cells, you have to specify the Grid..::.Row and Grid..::.Column properties.

  6. In the start tag for the Name TextBlock, add the following properties.

    Grid.Row="0" Grid.Column="0"
    

    Notice that the properties are named Grid..::.Row and Grid..::.Column instead of just Row and Column. Grid has Row and Column properties, but TextBlock does not. However, you can "attach" the Row and Column properties from Grid to the TextBlock. Grid..::.Row and Grid..::.Column are special properties called attached properties. Attached properties is a concept that you will use in XAML. For more information, see Attached Properties Overview.

  7. In the start tag for the Date TextBlock, add the following properties.

    Grid.Row="1" Grid.Column="0"
    
  8. In the start tag for the Message TextBlock, add the following properties.

    Grid.Row="2" Grid.Column="0"
    

    In the Preview window, the TextBlock elements are now positioned in the appropriate cells.

  9. Add the following ColumnSpan attached property to the Message TextBlock to allow the text to span across both columns.

    Grid.ColumnSpan="2"
    
  10. From the Toolbox, drag a TextBox control to just after the Message TextBlock.

  11. In the start tag, set the following properties.

    <TextBox Text="Your Name" Grid.Row="0" Grid.Column="1"></TextBox>
    

    Notice that the TextBox fills up the entire Grid cell. It fills the cell because the HorizontalAlignment and the VerticalAlignment properties are set to Stretch by default.

  12. In the start tag for the TextBox, set the Width property to 150.

    Width="150"
    

    Notice that the TextBox is centered in the Grid cell.

  13. In the start tag for the TextBox, set the alignment to left, by adding the following HorizontalAlignment property.

    HorizontalAlignment="Left"
    
  14. Below the Your Name TextBox, drag a StackPanel control from the Toolbox.

    A StackPanel is a useful control to stack elements vertically or horizontally. In the Grid cell below the Your Name TextBox, you will stack two controls vertically.

  15. In the start tag for the StackPanel, add the following properties.

    Grid.Column="1" Grid.Row="1" Orientation="Vertical"
    
  16. From the Toolbox, drag a Calendar control to within the StackPanel element.

    When you add the Calendar control, you will notice that the tag name is slightly different than the other controls. It is prefixed with "basics:" (or another prefix). The Calendar control is not part of the core Silverlight controls and is implemented in a different assembly. The Calendar control is part of the Silverlight SDK. To use the Silverlight SDK controls, you must add an XML namespace and a reference to the assembly. When you drag a Silverlight SDK control to XAML view, an XML namespace and a reference are added automatically at the top of the Page.xaml file in the <UserControl> tag. As can be see in the following markup, the basics namespace uses the System.Windows.Controls.dll assembly.

    <UserControl xmlns:basics="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls"
    

    For more information about the Silverlight SDK and the controls in the Silverlight SDK, see Silverlight Tools and Controls by Function.

  17. In the start tag for the Calendar, set the following properties.

    Setting the SelectionMode to SingleDate specifies to allow only a single date to be selected.

    SelectionMode="SingleDate" HorizontalAlignment="Left"
    
  18. From the Toolbox, drag a Button control to just after the Calendar control, but within the StackPanel element.

    Since the Orientation property of the StackPanel is set to Vertical, the Button appears after the Calendar.

  19. In the start tag for the Button, set the Width, Height, HorizontalAlignment, and Content properties.

    <Button Width="75" Height="25" HorizontalAlignment="Left" Content="OK"></Button>
    

    A Button control does not have a Text property, but it does have a Content property. A Button has a Content property because you can actually add other elements, such as images or other controls, as the content for a Button.

  20. On the File menu, click Save All.

    At this point, all of the controls have been added. Your XAML should be similar to the following.

    <UserControl xmlns:basics="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls"  x:Class="HelloSilverlight.Page"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
        Width="400" Height="300">
        <Grid x:Name="LayoutRoot" Background="Beige" ShowGridLines="True">
            <Grid.RowDefinitions>
                <RowDefinition Height="40"/>
                <RowDefinition Height="220"/>
                <RowDefinition Height="40"/>
            </Grid.RowDefinitions>
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="75" />
                <ColumnDefinition Width="325"/>
            </Grid.ColumnDefinitions>
            <TextBlock Text="Name:" Grid.Row="0" Grid.Column="0"></TextBlock>
            <TextBlock Text="Date:" Grid.Row="1" Grid.Column="0"></TextBlock>
            <TextBlock Text="Message:" Grid.Row="2" Grid.Column="0" Grid.ColumnSpan="2"></TextBlock>
            <TextBox Text="Your Name" Grid.Row="0" Grid.Column="1" Width="150" HorizontalAlignment="Left"></TextBox>
            <StackPanel Grid.Column="1" Grid.Row="1" Orientation="Vertical">
                <basics:Calendar SelectionMode="SingleDate" HorizontalAlignment="Left"></basics:Calendar>
                <Button Width="75" Height="25" HorizontalAlignment="Left" Content="OK"></Button>
            </StackPanel>
        </Grid>
    </UserControl>
    
  21. Press F5 or click Start Debugging to run the application.

    The following illustration shows an example of the browser window. You can type text in the TextBox, you can select dates in the Calendar, but the Button does not do anything because code has not been added yet.

    Grid layout with controls in browser
Adding Code

Code-behind files allow you to add logic to the elements defined in XAML. To access controls and other elements programmatically, the elements have to be named. This section describes how to name your elements in XAML, add an event handler, and add logic in the code-behind file.

To add code

  1. In XAML view, locate the Message TextBlock.

  2. In the start tag for the Message TextBlock, add the following message1 Name property.

    x:Name="message1"
    

    The x:Name attribute uniquely identifies an element. For more information, see XAML Overview.

  3. In a similar fashion, name the TextBox control name1, the Calendar control cal1, and the Button control okButton.

    x:Name="name1"
    x:Name="cal1"
    x:Name="okButton"
    
  4. In the start tag for the OK Button, type Click and then press TAB.

    An IntelliSense box should appear as shown in the following illustration.

    IntelliSense for new event handler
  5. Double-click <New Event Handler>.

    The default name for the Click event handler appears in XAML (Click="okButton_Click") and an event handler is created in the code-behind file.

  6. Right-click Click="okButton_Click" and in the shortcut menu, select Navigate to Event Handler as shown in the following illustration.

    Navigate to Event Handler shortcut menu

    Page.xam.vb or Page.xaml.cs is opened and the cursor is positioned in the okButton_Click event handler.

  7. On the Build menu, click Build Solution.

    Building the solution ensures that IntelliSense includes the controls that were just named.

  8. Add the following code to the okButton_Click event handler.

    Visual Basic
    Private Sub okButton_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)
        Dim dateString As String
        If cal1.SelectedDate Is Nothing Then
            dateString = "<date not selected>"
        Else
            dateString = cal1.SelectedDate.ToString()
        End If
        message1.Text = "Hi " & name1.Text & vbCrLf & _
            "Selected Date: " & dateString
    End Sub
    
    C#
    private void okButton_Click(object sender, RoutedEventArgs e)
    {
        string dateString;
        if (cal1.SelectedDate == null)
        {
            dateString = "<date not selected>";
        }
        else
        {
            dateString = cal1.SelectedDate.ToString();
        }
        message1.Text = "Hi " + name1.Text + "\n" +
            "Selected Date: " + dateString;
    }
    
  9. Press F5 or click Start Debugging to run the application.

  10. Type your name in the Name box, select a date in the Calendar, and then click OK.

    Your name and selected date is displayed. The following illustration shows an example of the browser window.

    Controls and running code in browser
Making the Layout Dynamic

The current layout is fixed. Silverlight includes various options to make dynamic layouts. This section describes techniques to make your layout more dynamic.

To make the layout dynamic

  1. In XAML view within the UserControl element, delete the Width and Height properties.

  2. In the Grid..::.RowDefinitions element, change the Height values to the following.

    <RowDefinition Height="Auto"/>
    <RowDefinition Height="*" MinHeight="240"/>
    <RowDefinition Height="Auto"/>
    

    Auto sizing indicates that the size is determined by the contents. Star sizing (*) indicates that the size is a weighted proportion of the remaining space.

  3. In the Grid..::.ColumnDefinitions element, change the Width values to the following.

    <ColumnDefinition Width="Auto" />
    <ColumnDefinition Width="*"/>
    
  4. Add the following Margin property to the Name, Date, and Message TextBlock elements.

    This indicates to add a 10 pixel margin on the left and right, and a 5 pixel margin on the top and bottom.

    Margin="10,5,10,5"
    
  5. Add the following Margin property to the TextBox, Calendar, and Button.

    Margin="0,5,0,5"
    
  6. Add the following FontSize property to the Message TextBlock to increase the size of the font.

    FontSize="20"
    
  7. On the File menu, click Save All.

    Your XAML should be similar to the following.

    XAML
    <UserControl xmlns:basics="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls"  x:Class="HelloSilverlight.Page"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
        >
        <Grid x:Name="LayoutRoot" Background="Beige" ShowGridLines="True">
            <Grid.RowDefinitions>
                <RowDefinition Height="Auto"/>
                <RowDefinition Height="*" MinHeight="240"/>
                <RowDefinition Height="Auto"/>
            </Grid.RowDefinitions>
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="Auto" />
                <ColumnDefinition Width="*"/>
            </Grid.ColumnDefinitions>
            <TextBlock Text="Name:" Grid.Row="0" Grid.Column="0" Margin="10,5,10,5"></TextBlock>
            <TextBlock Text="Date:" Grid.Row="1" Grid.Column="0" Margin="10,5,10,5"></TextBlock>
            <TextBlock x:Name="message1" Text="Message:" Grid.Row="2" Grid.Column="0" Grid.ColumnSpan="2" Margin="10,5,10,5" FontSize="20"></TextBlock>
            <TextBox x:Name="name1" Text="Your Name" Grid.Row="0" Grid.Column="1" Width="150" HorizontalAlignment="Left" Margin="0,5,0,5"></TextBox>
            <StackPanel Grid.Column="1" Grid.Row="1" Orientation="Vertical">
                <basics:Calendar x:Name="cal1" SelectionMode="SingleDate" HorizontalAlignment="Left" Margin="0,5,0,5"></basics:Calendar>
                <Button Click="okButton_Click" x:Name="okButton" Width="75" Height="25" HorizontalAlignment="Left" Content="OK" Margin="0,5,0,5"></Button>
            </StackPanel>
        </Grid>
    </UserControl>
    
  8. Press F5 or click Start Debugging to run the application.

    Notice that the Silverlight plug-in fills the browser window.

  9. Resize the browser window and note the behavior.

  10. Click the OK Button.

    Notice that the third row of the Grid increases in height to accommodate the text as shown in the following illustration.

    Dynamic layout in browser
Next Steps

This walkthrough has shown you some of the basics of creating an application for Silverlight. Hopefully it gave you a sense of the capabilities of Silverlight and how you create applications. To learn how to create more sophisticated designs and animations, see Walkthrough: Creating a Silverlight Clock by Using Expression Blend or Code.

See Also

Concepts

Other Resources

Page view tracker