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.
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
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.
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.
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.
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.
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
Click the white rectangular area in Design view to select the Grid element.
By default, Silverlight projects include a Grid.
In the Properties window, find the Background property.
In the second column, click the down arrow to open the color picker.
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.
In XAML view, find the Grid element.
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.
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
Make sure the Grid is still selected.
In the Properties window, find the ShowGridLines property.
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.
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.
Click the left grid rail to add a horizontal gridline.
Drag the gridline so that it is about 45 units from the top.
The position appears as a number in the grid rail.
Add another horizontal gridline about 45 units from the bottom.
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>
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.
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
Open the Toolbox window if it is not already open.
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" />
Drag another TextBlock control to the second row and first column.
Drag a TextBox control to the first row and second column.
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.
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.
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.
Drag a TextBlock control just under the Calendar control, but within the StackPanel.
Drag a Button control to the third row and second column of the Grid.
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.
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
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.
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.
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.
In the Document Outline window, move your mouse over the different elements and notice that a thumbnail preview is displayed for the elements.
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
Select the TextBlock in the first row and first column of the Grid.
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.
Set the Margin property to 10.
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:" ... />
Select the TextBlock in the second row.
In the Properties window, set the following properties.
Select the TextBox control in the first row.
At the top of the Properties window, change the Name property to name1.
In the Properties window, click to select the Margin property and then click the down arrow in the second column.
The margin editor appears.
Set the left, top, right, and bottom margin values to 0,10,0,10.
Set the Text property to Your Name.
Select the Calendar control.
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.
In the Properties window, set the following properties.
Property
Value
cal1
Left
In the Properties window, set the following properties.
Select the Button control.
In the Properties window, set the following properties.
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.
On the File menu, click Save All.
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.
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
Select the Grid control.
Move your mouse pointer over grid rail of the first row.
A sizing bar appears.
On the sizing bar, click Auto.
This causes the height of the first row to adjust depending on its contents.
Using the sizing bar, set the third row to Auto.
Using the sizing bar, set the first column to Auto.
Run the application.
Resize the window.
Notice that the first row, third row, and first column maintain their size.
Close your browser to return to Visual Studio.
Select the first TextBlock.
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.
Select the TextBox.
On the right side of the TextBox, move your mouse pointer over the small circle until your pointer changes to pointing finger.
Click the small circle to add a margin line that extends to the right side of the design surface.
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>
Run the application.
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
Select the Button.
At the top of the Properties window, click the Events tab.
All of the events for the Button are listed.
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.
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; }
On the File menu, click Save All.
Run the application.
Type your name in the name box, select a date in the Calendar, and then click OK.
Your name and selected date are displayed.
For more information about event handlers, see Getting Started with Controls.
See Also
Concepts
Other Resources
Change History
Date |
History |
Reason |
---|---|---|
July 2010 |
Updated to include new features in the designer. |
Information enhancement. |