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 4 Beta.

  • Silverlight Tools for Visual Studio 2010 Beta 2.

  • Silverlight SDK (part of the Silverlight Tools for Visual Studio 2010 Beta 2).

  • Visual Studio 2010 Beta 2.

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#. Clear the Host the Silverlight application in a new Web site check box. For more information, see How to: Create a New Silverlight Project.

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

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

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

    MainPage.xaml.vb or MainPage.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 MainPage.xaml is not already open, double-click it in Solution Explorer.

    In the center of Visual Studio, you should see a white rectangular area. This area is called Design view. You can drag controls from the Toolbox and position elements to create your layout.

    Below Design view is XAML view. XAML view is where you can add XAML to create your layout. As you make changes to XAML view, Design view is automatically updated. 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.

    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, Design view 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 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.

    XAML
    <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 Design view, you see lines appear that identify the rows and columns.

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

    Your browser opens and you see dotted lines that indicate the Grid that you defined, 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.

    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 Design view, 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"
    
  9. Add the following ColumnSpan attached property to the Message TextBlock to allow the text to span across both columns.

    Grid.ColumnSpan="2"
    

    In Design view, the TextBlock elements are now positioned in the appropriate cells.

  10. From the Toolbox, drag a TextBox control to just after the Message TextBlock in XAML view.

  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.

    Controls added to Silverlight layout
  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 to XAML view.

    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 in XAML view.

    When you add the Calendar control, you will notice that the tag name is slightly different than the other controls. It is prefixed with controls: (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 or Design view, an XML namespace and a reference are added automatically at the top of the MainPage.xaml file in the <UserControl> tag. As can be see in the following markup, the controls namespace uses the System.Windows.Controls.dll assembly.

    <UserControl xmlns:controls="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 in XAML view.

    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.

    XAML
    <UserControl
        xmlns:controls="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls"
        x:Class="HelloSilverlight.MainPage"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
        mc:Ignorable="d" d:DesignWidth="400" d:DesignHeight="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">
                <controls:Calendar SelectionMode="SingleDate"
                    HorizontalAlignment="Left"></controls: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 window 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

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

  7. 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;
    }
    
  8. Press F5 or click Start Debugging to run the application.

  9. 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 MainPage.xaml, in the Grid..::.RowDefinitions element, change the Height values to the following.

    <RowDefinition Height="Auto"/>
    <RowDefinition Height="*" MinHeight="220"/>
    <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.

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

    <ColumnDefinition Width="Auto" />
    <ColumnDefinition Width="*"/>
    
  3. 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"
    
  4. Add the following Margin property to the TextBox, Calendar, and Button.

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

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

    Your XAML should be similar to the following.

    XAML
    <UserControl
        xmlns:controls="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls"
        x:Class="HelloSilverlight.MainPage"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
        mc:Ignorable="d" d:DesignWidth="400" d:DesignHeight="300">
        <Grid x:Name="LayoutRoot" Background="Beige" ShowGridLines="True">
            <Grid.RowDefinitions>
                <RowDefinition Height="Auto"/>
                <RowDefinition Height="*" MinHeight="220"/>
                <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">
                <controls:Calendar x:Name="cal1" SelectionMode="SingleDate"
                    HorizontalAlignment="Left" Margin="0,5,0,5"></controls: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>
    
  7. Press F5 or click Start Debugging to run the application.

  8. Resize the browser window and note the behavior.

  9. 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
See Also

Concepts

Other Resources

Page view tracker