Compartir a través de


Walkthrough: Creating Your First Silverlight Application

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

Updated: July 2010

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.

  • Adding core controls and Silverlight SDK controls.

  • Selecting elements and setting properties.

  • Creating an event handler and adding code.

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:

  • Visual Studio 2010.

  • Silverlight Tools for Visual Studio 2010.

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. This section describes how to create new Silverlight project in Visual Studio.

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. As you make changes to Design view, XAML view is automatically updated, and as you make changes in XAML view, Design view is updated. There are many features that help you work in Design view, such as resizing handles and snaplines. 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 Designer for Visual Studio 2010.

    New Silverlight project in Visual Studio

Setting the Background Color

Visual Studio provides several options and windows to visually create your application. This section shows you how to start customizing your application by setting the background color using the Properties window and XAML view.

To set the background color

  1. Click the white rectangular area in Design view to select the Grid element.

    By default, Silverlight projects include a Grid.

  2. In the Properties window, find the Background property.

  3. In the second column, click the down arrow to open the color picker.

    Color picker

  4. Use the various controls to select a color.

    Design view updates with the new color.

    You can also set the background color manually in XAML view. XAML is an XML-based declarative language that you use to define your user interface (UI). For more information about XAML, see XAML Overview.

  5. In XAML view, find the Grid element.

  6. In the Grid start tag, change the Background color by typing 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

Defining the Grid Layout

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.

To define the Grid layout

  1. Make sure the Grid is still selected.

  2. In the Properties window, find the ShowGridLines property.

  3. In the second column, add a check mark to enable this property.

    In XAML view, notice that that the ShowGridLines property for the Grid is set to True.

    <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. Move your mouse pointer along the left or top edge of the Grid in Design view.

    The left and top edges are called grid rails. Your mouse pointer changes to cross hairs and a horizontal or a vertical line appears.

    Adding gridlines

  5. Click the left grid rail to add a horizontal gridline.

  6. Drag the gridline so that it is about 45 units from the top.

    The position appears as a number in the grid rail.

  7. Add another horizontal gridline about 45 units from the bottom.

    Adding rows and columns with the designer.

  8. Add a vertical gridline about 100 units from the left.

    When the columns and rows are added in Design view, the following markup is added in XAML view.

    <Grid x:Name="LayoutRoot" Background="Beige" ShowGridLines="True">
     <Grid.ColumnDefinitions>
        <ColumnDefinition Width="100*" />
        <ColumnDefinition Width="300*"/>
     </Grid.ColumnDefinitions>
     <Grid.RowDefinitions>
         <RowDefinition Height="45*"/>
         <RowDefinition Height="210*"/>
         <RowDefinition Height="45*"/>
     </Grid.ColumnDefinitions>
    </Grid>
    
  9. 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

  10. 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 the first row and first column of the Grid.

    The following markup is added to XAML view.

    <TextBlock Height="23" HorizontalAlignment="Left" Margin="12,12,0,0" 
    Name="textBlock1" VerticalAlignment="Top" />
    
  3. Drag another TextBlock control to the second row and first column.

  4. Drag a TextBox control to the first row and second column.

  5. Drag a StackPanel control to the second row and second column.

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

  6. Right-click the StackPanel, click Reset Layout, and then click All.

    The StackPanel fills the grid cell. The All command removes all of the absolute size and position settings.

  7. Drag a Calendar control to within the StackPanel element.

    When you add the Calendar control, notice that the tag name in XAML view is slightly different than the other controls. It is prefixed with sdk:. 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 Design view or XAML view, an XML namespace is added automatically at the top of the MainPage.xaml file in the <UserControl> tag. As can be seen in the following markup, the sdk namespace uses a specific URI as described in Prefixes and Mappings for Silverlight Libraries.

    <UserControl xmlns:sdk="https://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk"
    

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

  8. Drag a TextBlock control just under the Calendar control, but within the StackPanel.

  9. Drag a Button control to the third row and second column of the Grid.

  10. Run the application.

    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.

    Controls added

  11. Resize the window and note the behavior.

Selecting Elements

As you add more controls and elements to your application, it becomes harder to locate and select the element that you want to work with. This section describes how you can select elements in Design view, XAML view, and the Document Outline window.

To select elements

  1. In Design view, click to select the Button.

    Notice that the Button is also selected in XAML view and the Properties window displays the Button properties.

  2. In XAML view, click anywhere within the first TextBlock element.

    The TextBlock is selected in Design view and the Properties window displays the TextBlock properties.

  3. To open the Document Outline window, click the View menu, click Other Windows, and then click Document Outline.

    The Document Outline window enables you to view and select elements in your application in a hierarchical way.

  4. In the Document Outline window, move your mouse over the different elements and notice that a thumbnail preview is displayed for the elements.

    Document Outline window

  5. Click to select an element.

    Notice that Design view, XAML view, and the Properties window changes selection. For more information about how to use the Document Outline window, see Navigating XAML Elements with the Document Outline Window.

Setting Control Properties

In Visual Studio, there are different ways that you can set properties. This section shows how to set control properties using the Properties window.

To set control properties

  1. Select the TextBlock in the first row and first column of the Grid.

  2. At the top of the Properties window, in the Search box, type margin.

    The properties in the Properties window are filtered to just show the Margin property.

    Search box in the Properties window

  3. Set the Margin property to 10.

  4. Find the Text property and set it to Name:.

    The following shows how the TextBlock property changes appear in XAML view.

    <TextBlock Margin="10" Text="Name:" ... />
    
  5. Select the TextBlock in the second row.

  6. In the Properties window, set the following properties.

    Property

    Value

    Margin

    10

    Text

    Date:

  7. Select the TextBox control in the first row.

  8. At the top of the Properties window, change the Name property to name1.

    Name box in the Properties window

  9. In the Properties window, click to select the Margin property and then click the down arrow in the second column.

    The margin editor appears.

  10. Set the left, top, right, and bottom margin values to 0,10,0,10.

    Margin editor

  11. Set the Text property to Your Name.

  12. Select the Calendar control.

  13. Right-click the Calendar, click Reset Layout, and then click All.

    The Calendar fills the available space. The All command removes all of the absolute size and position settings.

  14. In the Properties window, set the following properties.

    Property

    Value

    Name

    cal1

    HorizontalAlignment

    Left

  15. Select the TextBlock below the Calendar.

  16. In the Properties window, set the following properties.

    Property

    Value

    Name

    message1

    FontSize

    20

    Height

    Auto

    Text

    Message:

  17. Select the Button control.

  18. In the Properties window, set the following properties.

    Property

    Value

    Name

    okButton

    Content

    OK

    Margin

    0,10,0,10

    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.

  19. On the File menu, click Save All.

  20. 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

  21. Resize the window.

    Note that the rows and columns change size.

Adjusting the Layout

Many applications need to support different screen sizes. This section describes some adjustments that you can make to the layout so that the application behaves correctly when it is resized.

To adjust the layout

  1. Select the Grid control.

  2. Move your mouse pointer over grid rail of the first row.

    A sizing bar appears.

    Sizing bar

  3. On the sizing bar, click Auto.

    This causes the height of the first row to adjust depending on its contents.

  4. Using the sizing bar, set the third row to Auto.

  5. Using the sizing bar, set the first column to Auto.

  6. Run the application.

  7. Resize the window.

    Notice that the first row, third row, and first column maintain their size.

  8. Close your browser to return to Visual Studio.

  9. Select the first TextBlock.

  10. Change its Text property to First Name:.

    Notice how the width of the first column automatically adjusts. This is because you set the width to Auto.

  11. Select the TextBox.

  12. On the right side of the TextBox, move your mouse pointer over the small circle until your pointer changes to pointing finger.

  13. Click the small circle to add a margin line that extends to the right side of the design surface.

    Margin line

    The margin line anchors the TextBox to the right side of the window causing it to be resized when the window is resized.

    At this point, all of the controls have been added, and their properties set. Your XAML should now look like the following.

    
    <UserControl
        xmlns:sdk="https://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk"
        x:Class="HelloSilverlight.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" d:DesignWidth="400" d:DesignHeight="300">
        <Grid x:Name="LayoutRoot" Background="Beige" ShowGridLines="True">
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="Auto" />
                <ColumnDefinition Width="300*" />
            </Grid.ColumnDefinitions>
            <Grid.RowDefinitions>
                <RowDefinition Height="Auto" />
                <RowDefinition Height="210*" />
                <RowDefinition Height="Auto" />
            </Grid.RowDefinitions>
    
            <TextBlock Height="23" HorizontalAlignment="Left" Margin="10" 
                Name="textBlock1" Text="First Name:" VerticalAlignment="Top" />
            <TextBlock Grid.Row="1" Height="23" HorizontalAlignment="Left" 
                Margin="10" Name="textBlock2" Text="Date:" VerticalAlignment="Top" />
            <TextBox Grid.Column="1" Height="23" Margin="0,10,194,0" Name="name1" 
                VerticalAlignment="Top" Text="Your Name" />
            <StackPanel Grid.Column="1" Grid.Row="1" Name="stackPanel1">
                <sdk:Calendar Name="cal1" HorizontalAlignment="Left" />
                <TextBlock Height="Auto" Name="message1" Text="Message:" 
                    FontSize="20" />
            </StackPanel>
            <Button Content="OK" Grid.Column="1" Grid.Row="2" Height="23" 
                HorizontalAlignment="Left" Margin="0,10" Name="okButton" 
                VerticalAlignment="Top" Width="75" />
        </Grid>
    </UserControl>
    
    
  14. Run the application.

  15. Resize the window.

    Notice that the width of the TextBox changes as you resize the window.

Creating an Event Handler

Each control has events that enable you to respond to actions from the user. You create a method, called an event handler, to handle the event. To access controls and other elements programmatically, the elements have to be named. Previously in this walkthrough, you set the Name property for most of the controls you added to the application. This section describes how to create an event handler and add logic in the code-behind file.

To create an event handler

  1. Select the Button.

  2. At the top of the Properties window, click the Events tab.

    All of the events for the Button are listed.

    Events tab

  3. Double-click the Click event.

    A default event handler for the Button is created. MainPage.xaml.vb or MainPage.xaml.cs is opened and the cursor is positioned in the okButton_Click event handler.

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

    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
    
    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;
    }
    
  5. On the File menu, click Save All.

  6. Run the application.

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

    Your name and selected date are displayed.

    Dynamic layout in browser

    For more information about event handlers, see Getting Started with Controls.

Change History

Date

History

Reason

July 2010

Updated to include new features in the designer.

Information enhancement.