Powered by

US - English
NEW! Silverlight 5 is available Learn More

Working with Panels, XAML and Controls

By Microsoft Silverlight Team|December 1, 2010|Level 200 : Novice

Contents

Overview

You Will Benefit from this Lab if:

  • You are new to Silverlight
  • You are in need of a basic primer that’s business focused
  • You want to get a better understanding of how a Silverlight project is structured

You Will Learn:

  • How to use the Visual Studio 2010 Silverlight Designer, Cider
  • XAML, Panels, and Controls
  • The difference between a Grid and a StackPanel
  • How to add controls
  • XML Namespaces
  • How to create a UserControl

Business Requirements for the Silverlight application include:

  • Create a data driven interface with a DataGrid
  • Handle user interface events
  • Use XAML to create a data entry form
  • Handle the hiding and showing of the data input screen
  • Used the StackPanel to encapsulate the applications menu

Exercise 1: Creating a Data-Driven Interface

Watch Video

Estimated Time: 45 minutes

Working with XAML is very similar to working with HTML, the main advantage being that you don’t have to worry about the pesky cross browser issues. Like HTML, XAML is XML. There are nodes, which define controls and attributes which are properties of the control. This exercise shows how to work with XAML, how to work with controls by adding a DataGrid, and how to work with the visual editor, known as the Cider editor, in Visual Studio.

  1. Open the starter solution, and go to MainPage.xaml
  2. Define rows in the Grid, LayoutRoot, by using the tag. Inside the tag, place a for each intended row. The resulting Layoutroot should look like this:

    XAML

    <Grid x:Name="LayoutRoot" Background="White">
       <Grid.RowDefinitions>
         <RowDefinition Height="Auto"/>
         <RowDefinition Height="Auto"/>
      </Grid.RowDefinitions>
    </Grid>
    

    It’s important to note that you won’t place any tags specifying the beginnings and ends of rows inside the grid, itself. Instead, row assignment is specified as an attribute inside each control tag.

  3. Add a TextBlock control to serve as the application title. The row placement is specified using the Grid.Row attribute inside the TextBlock tag, as seen in the following Xaml.

    XAML

    <Grid x:Name="LayoutRoot" Background="White">
            <Grid.RowDefinitions>
                    <RowDefinition Height="Auto"/>
                    <RowDefinition Height="Auto"/>
            </Grid.RowDefinitions>
            <TextBlock Height="Auto" Width="Auto" Grid.Row="0">
                    Contact Details
            </TextBlock>
    </Grid>
    

    Rows are indexed from the top of the panel to the bottom, beginning with zero.

  4. Next, open the Toolbox on the left hand side of the screen and locate the DataGrid control. Drag and drop the DataGrid onto the design view below the header. Take a look at the XAML generated by Visual Studio for the DataGrid conrol. The ‘sdk:’ at the beginning of the tag denotes an xmlns(XML Namespace)declaration. At the top of the page, you can see where this declaration was included with the others. This is a necessary addition if you want to use the DataGrid, as it is part of the Silverlight Toolkit and not part of the native runtime.

    XAML

    d:DesignHeight="566" d:DesignWidth="947"    xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk">
    <Grid x:Name="LayoutRoot" Background="White">
            <Grid.RowDefinitions>
                    <RowDefinition Height="Auto"/>
                    <RowDefinition Height="Auto"/>
            </Grid.RowDefinitions>
            <TextBlock Height="Auto" Width="Auto" Grid.Row="0">
                    Contact Details
            </TextBlock>
            <sdk:DataGrid AutoGenerateColumns="True" Grid.Row="1" Height="Auto"
     Width="Auto" HorizontalAlignment="Left" Margin="0,0,16,0" 
     Name="dataGrid1" VerticalAlignment="Top"/>
    </Grid>
    
  5. Add data to the DataGrid. (For the purposes of this lab, the DataGrid is populated with a Sample Data Collection generated from Expression Blend. However, you can use your own web service, XML files, or C# class data to populate the DataGrid.) By setting Height and Width to ‘Auto’, the Grid dynamically resizes itself based on the size of the content. Here’s the finished XAML:

    XAML

    <UserControl.Resources>
            <DataTemplate x:Key="ImageTemplate">
                    <StackPanel>
                            <Image Source="{Binding Image}" HorizontalAlignment="Left"
     Height="64" Width="64"/>
                    </StackPanel>
            </DataTemplate>
    </UserControl.Resources>
    <Grid x:Name="LayoutRoot" Background="White" DataContext="{Binding Source={StaticResource Contacts}}">
            <Grid.RowDefinitions>
                    <RowDefinition Height="Auto"/>
                    <RowDefinition Height="Auto" />
            </Grid.RowDefinitions>
            <TextBlock Height="Auto" Width="Auto" Grid.Row="0" FontSize="24"
     HorizontalAlignment="Left" VerticalAlignment="Top"
     Margin="8,8,0,0">Contact Details</TextBlock>
            <sdk:DataGrid AutoGenerateColumns="False" Grid.Row="1" Height="Auto" 
     Width="Auto" HorizontalAlignment="Left" Margin="0,16,0,0" 
     x:Name="ContactsDataGrid" VerticalAlignment="Top" 
     ItemsSource="{Binding Collection}">
                    <sdk:DataGrid.Columns>
                    <sdk:DataGridTextColumn Binding="{Binding Name}" Header="Name"/>
                    <sdk:DataGridTemplateColumn CellTemplate="{StaticResource 
     ImageTemplate}" Header="Image"/>
                    <sdk:DataGridTextColumn Binding="{Binding Address}" 
     Header="Address"/>
                    <sdk:DataGridTextColumn Binding="{Binding Email}" Header="Email"/>
                    <sdk:DataGridTextColumn Binding="{Binding PhoneNumber}" 
     Header="PhoneNumber"/>
                    <sdk:DataGridTextColumn Binding="{Binding WebSite}" 
     Header="WebSite"/>
                    </sdk:DataGrid.Columns>
            </sdk:DataGrid>
    </Grid>
    
    And here’s what it looks like :

Exercise 2: Creating a Form Entry to Edit Interface Details

Creating an UI for an entry form lends itself to the creation of a page. In ASP.NET you would create a WebForm. In a Silverlight project, a UserControl used to create a new page. In this exercise you will learn how to create a new UserControl and create a data entry form.

  1. To add a new UserControl, right click on the solution name in the solution explorer and select ‘add → New Item’.
  2. Select Silverlight User Control from the menu
  3. Rename the Control to ‘EditDetails.xaml’ in the bottom of the Add New Item window, and click ‘Add’.
  4. Next create the form entries for each field in the DataGrid (Name, Image, Address, Email, Phone number, and Website). Using the Toolbox in Visual Studio, add 6 TextBox controls. Edit the ‘Text’ attribute for each block to add default text.

    XAML

    <TextBox Height="23" HorizontalAlignment="Left" Margin="12,16,0,0" Name="textBox1" VerticalAlignment="Top" Width="348" Text="Name" />
    <TextBox Height="23" HorizontalAlignment="Left" Margin="12,46,0,0" Name="textBox2" VerticalAlignment="Top" Width="348" Text="Image Location"/>
    <TextBox Height="23" HorizontalAlignment="Left" Margin="12,74,0,0" Name="textBox3" VerticalAlignment="Top" Width="348" Text="Address"/>
    <TextBox Height="23" HorizontalAlignment="Left" Margin="12,104,0,0" Name="textBox4" VerticalAlignment="Top" Width="348" Text="Email"/>
    <TextBox Height="23" HorizontalAlignment="Left" Margin="10,134,0,0" Name="textBox5" VerticalAlignment="Top" Width="350" Text="Phone Number"/>
    <TextBox Height="23" HorizontalAlignment="Left" Margin="10,164,0,0" Name="textBox6" VerticalAlignment="Top" Width="350" Text="Website"/>
    
  5. Place the new UserControl inside the MainPage View. Before you can do that, you must build the project in order the UserControl to show up in the Toolboox.
  6. Select MainPage.xaml and open the Toolbox. There should be a new entry at the top of your list.

    You must have a page other than EditContacts.xaml as your currently open document for EditContacts to appear in the toolbox.

  7. Much like adding the DataGrid, add the EditContacts UserControl by dragging and dropping onto the design view.
  8. Look at the Xaml and notice there is a new xml namespace, xmlns:my. This represents the current project, and lets the runtime know where to find the control.

    XAML

    xmlns:my="clr-namespace:PanelsControlsLab"
    
  9. At the top of the page, add a button to enable the user to open up the Add Contact interface. Drag and Drop a ToggleButton onto the design view. You can edit the Content attribute of the ToggleButton to say “Add new contact”.

    If you don’t see the ToggleButton in the Toolbox, add it by right clicking the Toolbox and select Choose Items from the context menu.

    From the Choose Toolbox Items dialog box, Find and select the ToggleButton. Now the ToggleButton is added to the Toolbox, find it and click and add it to your UI.

  10. The EditContacts UserControl should only be visible when the ToggleButton is checked, make sure this window doesn’t open by default. Right click on the EditDetails control and click properties to open the properties window. By default, the Properties panel opens in the bottom right and corner of the screen.

    In this window you can edit the visual properties of whatever control you have selected at the moment. For now, you want the default visibility set to Collapsed.

  11. Next, wire up that ToggleButton to hide and show the EditDetails control. In order to set this property, add an event handler to the code-behind.

    There’s a shortcut if you want to add an Event Handler. If you select “Events” in the properties window of the CheckBox control, you’ll see an event labeled Checked. Double-click that event to automatically generate the event handler for the CheckBox. Do the same once more for the UnChecked event.

  12. In the AddContactButton_Checked handler, set the visibility of the EditContacts control to System.Windows.Visibility.Visible. In the AddContactButton_UnChecked handler set it to System.Windows.Visibility.Collapsed. Your MainPage.xaml.cs or MainPage.xaml.vb should look like this:

    C#

    namespace PanelsControlsLab
    {
            public partial class MainPage : UserControl
            {
                    public MainPage()
                    {
                            InitializeComponent();
                    }
    
                    private void AddContactButton_Checked(object sender, 
     System.Windows.RoutedEventArgs e)
                    {
                            this.AddContactPanel.Visibility =  
     System.Windows.Visibility.Visible;
                    }
    
                    private void AddContactButton_Unchecked(object sender, 
     RoutedEventArgs e)
                    {
                            this.AddContactPanel.Visibility =System.Windows.Visibility.Collapsed;
                    }
            }
    }
    

    Visual Basic

    Namespace PanelsControlsLab
            Partial Public Class MainPage
                    Inherits UserControl
                    Public Sub New()
                            InitializeComponent()
                    End Sub
    
                    Private Sub AddContactButton_Checked(ByVal sender As Object,ByVal e As System.Windows.RoutedEventArgs)
                            Me.AddContactPanel.Visibility = System.Windows.Visibility.Visible
                    End Sub
    
                    Private Sub AddContactButton_Unchecked(ByVal sender As Object, ByVal e As RoutedEventArgs)
                            Me.AddContactPanel.Visibility = System.Windows.Visibility.Collapsed
                    End Sub
            End Class
    End Namespace
    
  13. Next add a button that will add the data entered in these fields into our DataGrid. Open EditContacts.xaml and drag a button onto the bottom of the UserControl. Set the text of the button to Add Contact.

    (A simple border around the edit contacts window has been added, and set the Height and Width of editContacts1 in MainPage.Xaml to ‘Auto’. This was done entirely for aesthetic purposes, and is optional).

    XAML

    <Button Content="Add Contact" Height="23" HorizontalAlignment="Left" Margin="224,194,0,0" Name="button1" VerticalAlignment="Top" Width="136" />
    <Border BorderThickness="1" Height="227" HorizontalAlignment="Left" Name="border1" VerticalAlignment="Top" Width="372">
            <Border.BorderBrush>
                    <LinearGradientBrush EndPoint="1,0.5" StartPoint="0,0.5">
                            <GradientStop Color="Black" Offset="0" />
                            <GradientStop Color="#FF443B3B" Offset="1" />
                    </LinearGradientBrush>
            </Border.BorderBrush>
    </Border>
    
  14. That’s it! Run your program to see the finished product. Here what it will look like:

Exercise 3: Add a Menu using the StackPanel

So far you’ve learned how to add controls, use the DataGrid, work with the Grid, and add event handlers. In this exercise you’ll take a look at another type of Panel, the StackPanel. The StackPanel is unique because it handles aligning the contained elements for you. By specifying the Orientation property. The can be organized either Vertically or Horizontally. In this case you are going to add two more menu items (edit contacts and help) next to the Add new contact button and align the StackPanel horizontally.

  1. Add a ToggleButton for editing the contacts and a Button for Help. Place the items next to the Add new contacts button. At this point you have your menu. Notice the margins and HorizontalAlignment of each button is set. For small scale applications, this is okay. However, what happens when you want to add more menu items, or better yet, if you are dynamically generating the menu.
  2. Create a StackPanel and move the controls inside. The below Xaml shows the how your menu should look.

    XAML

    <StackPanel HorizontalAlignment="Right" Margin="0,8,8,11"  
    Orientation="Horizontal">
            <ToggleButton x:Name="AddContactButton" Content="Add new contact" Checked="AddContactButton_Checked" Unchecked="AddContactButton_Unchecked" Height="24" Margin="0,0,5,0" />
            <ToggleButton x:Name="EditContactButton" Content="Edit contact" Checked="AddContactButton_Checked" Unchecked="AddContactButton_Unchecked" Height="24" Margin="0,0,5,0" />
            <Button x:Name="HelpButton" Content="Help"/>
    </StackPanel>
    
  3. And this is how the menu will look in Visual Studio

Summary

In this exercise you learned how to create a data driven Silverlight interface from the ground up. You added a data entry form to the existing prorject and created a menu with the StackPanel. In this application you satisfied the following requirements:

  • Create a data driven interface with a DataGrid
  • Handle user interface events
  • Use XAML to create a data entry form
  • Handle the hiding and showing of the data input screen
  • Used the StackPanel to encapsulate the applications menu

This lab is the foundation for creating a data driven Silverlight interface. Other labs will provide additional details about application design practices such as Model-View-ViewModel (MVVM), how to use Expression Blend, how to integrate services, and how to create desktop applications with Silverlight.

Microsoft Silverlight Team

By Microsoft Silverlight Team, Silverlight is a powerful development platform for creating engaging, interactive user experiences for Web, desktop, and mobile applications when online or offline.

Comments (0)