Powered by

US - English
NEW! Silverlight 5 is available Learn More

Controls Part 2

By Microsoft Silverlight Team|June 21, 2010|Level 100 : Beginner

Summary

Silverlight provides several controls to display content to users. This QuickStart introduces the different types of controls available for Silverlight and how to add content to those controls.

This QuickStart contains the following sections:

Layout Controls

Controls that contain other controls are often referred to as layout controls. Layout controls are containers for other controls and visual objects and as the name implies, layout controls are used to position these contained objects on the screen. A layout control serves as the "layout root" of your application. All other objects in your UI are contained in this root. You can use additional layout controls inside the layout root as needed.

Typically, layout controls derive from the Panel class. Some examples of layout controls include StackPanel, Canvas and Grid. When you create a Silverlight application in Visual Studio a Grid is created and set as the layout root of the application.

You set the contents for a layout control with the Children property, however when you create controls in XAML controls that are physical child elements of a container control are implicitly added to the Children collection. Children is a UIElementCollection, which means you can add any UIElement to the collection.

For more information on Silverlight layout controls and the layout system, see The Silverlight Layout System.

The following sample shows some of the layout controls. In this sample a StackPanel and a Canvas are nested in a Grid.

Layout Controls

The following shows the XAML for the previous example.

XAML

<Grid x:Name="LayoutRoot" Background="LightYellow" ShowGridLines="True" 
  Height="259" Width="429">
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="190*" />
        <ColumnDefinition Width="210*" />
    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
        <RowDefinition Height="*" />
        <RowDefinition Height="150" />
    </Grid.RowDefinitions>
    <TextBlock Margin="5" FontSize="10" 
     Text="Grid Row 0 - Star sized" Grid.ColumnSpan="2" />
    <TextBlock Margin="5,5,-66,-28" FontSize="10" 
    Grid.Row="1" Text="Grid Row 1 - Fixed size" Grid.ColumnSpan="2" />
    <StackPanel Grid.Row="1" Orientation="Horizontal" Grid.Column ="1">
        <TextBlock FontSize="10" Text="Horizontal StackPanel"  Margin="5"/>
        <TextBlock FontSize="10" Text="Row 1, Column 1" Margin="5" />
    </StackPanel>
    <Canvas Grid.Column="1" Grid.Row="0">
        <TextBlock Canvas.Left="20" Canvas.Top="20" 
        FontSize="10" Text="Canvas in Row 0, Column 1" Margin="5"/>
    </Canvas>
</Grid>

Text, Resource, Content and List Controls

The following example shows several Silverlight controls displaying content. Click the tabs to see the different types of controls.

Get Microsoft Silverlight

Text Controls

Text controls typically display string content. There are different types of text controls for different purposes. The following are examples of text controls.

  • TextBlock: Use this to display simple, read-only snippets of text.
  • TextBox: This is often used for short text input; however, you can also use it for larger, multi-line text input.
  • PasswordBox Masks the text a user inputs.
  • RichTextBox: Provides more advanced formatting features than the TextBox and TextBlock controls.

You set the content of the Textblock, TextBox and RichTextBox control. PasswordBox using the Text property. You set content for the RichTextBox using the Blocks property, which accepts a BlockCollection. Block is an abstract class, so you populate this collection with Paragraph, which derives from Block. In XAML, it is not necessary to set the Blocks property explicitly. You can add Paragraph elements to the RichTextBox. The following code example shows how to set content for the TextBlock, TextBox, PasswordBox, and RichTextBox controls.

XAML

<TextBlock Height="23" HorizontalAlignment="Left" 
    Margin="20,55,0,0" Name="textBlock1" Text="TextBlock" 
    VerticalAlignment="Top" Width="118" />
<TextBox Height="23" HorizontalAlignment="Left" 
    Margin="18,12,0,0" Name="textBox1" VerticalAlignment="Top" 
    Width="120" Text="TextBox" />
<PasswordBox Height="23" HorizontalAlignment="Left" 
    Margin="20,84,0,0" Name="passwordBox1" VerticalAlignment="Top" 
    Width="120" Password="password" />
<RichTextBox HorizontalAlignment="Left" Margin="20,128,0,0"  
    Name="richTextBox1" VerticalAlignment="Top" Width="120" > 
    <Paragraph>RichTextBox</Paragraph>
</RichTextBox>

For information about rendering text in your application, see Text and Rich Text QuickStart.

Resource Controls

Resource controls are designed to display resources such as video/audio, images, or HTML.

You set the content of resource controls with the Source property, which is typically an absolute or relative URL. The following example shows how to set the content for the Image and MediaElement controls. In both cases, the source files are relative to the application (XAP) file.

XAML

<Image Height="102" HorizontalAlignment="Left" 
    Margin="39,165,0,0" Name="image1" Stretch="Fill" 
    VerticalAlignment="Top" Width="97" Source="sdk-team.jpg"/>
<MediaElement Height="168" HorizontalAlignment="Left" 
    Margin="195,99,0,0" Name="mediaElement1" VerticalAlignment="Top"
    Width="248" Source="SilverlightControls.wmv" />

For more information about working with images, see Imaging QuickStart. For more information about working with media files, see Audio and Video QuickStart.

Content Controls

Content controls derive from the ContentControl class and can display varied content. You populate these controls with the Content property.

The following are examples of content controls.

You populate these controls with the Content property. The Content property is of type Object, so there are few restrictions on what a content control can contain. Because many classes that derive from Object can contain other controls, you can create nested content in a ContentControl. For example, you can set the Content property of a button to a StackPanel that contains an image and text. A TabItem control is a content control with the addition of a header property. The following example shows how to set content for the Label, Button, CheckBox and RadioButton controls.

XAML

<sdk:Label Height="28" Name="label1" Content="Label" 
     Width="120" Margin="18,6,322,287" />

<Button Height="23" HorizontalAlignment="Left" Margin="18,40,0,0" 
        Name="button1" VerticalAlignment="Top" Width="75" >
    <Button.Content>
        <StackPanel Orientation="Horizontal" >
            <Image Source="sdk-team.jpg"  />
            <TextBlock Text="Button"  />
        </StackPanel>
    </Button.Content>
</Button>

<CheckBox Content="CheckBox" Height="16" HorizontalAlignment="Left"  
          Margin="18,86,0,0" Name="checkBox1" VerticalAlignment="Top" 
          Width="81" IsChecked="True" />

<RadioButton Content="RadioButton" Height="16" HorizontalAlignment="Left" 
             Margin="18,124,0,0" Name="radioButton1" VerticalAlignment="Top" />

List Controls

Items Controls

Items controls are ideal for displaying a lists or collections of items. ListBox and TabControl are examples of items controls. You set the content for an items control with the Items or ItemsSource property. You use the Items property to populate a control directly. Use the ItemsSource property when want to display a data collection or to bind an ItemsControl to a collection object. Each items control has a content control that contains each piece of data for that control, whether the items are added explicitly or implicitly when the control is data bound. For example, a ListBox contains ListBoxItem controls.

Headered Items Controls

Headered items controls derive from the HeaderedItemsControl class and are very similar to items controls. Headered items controls include a Header property that sets the header content for the control. The Header property is an object so it can display many different types of content. The TreeView control is an example of a headered items control. Because it can display a header and additional content, the TreeView is ideal for displaying hierarchical data.

DataGrid

DataGrid is a special kind of list control that displays data in a highly customizable grid. You can set content for the DataGrid using ItemsSource only. For more information about the DataGrid control, see DataGrid.

The following example shows a ListBox, TreeView and DataGrid controls bound to the same data source. The TreeView control uses a HierarchicalDataTemplate to show the hierarchical data. For more information about how to use a HierarchicalDataTemplate and a TreeView together, see How to: Use a TreeView Control to Display Hierarchical Data.

XAML

<ListBox  Name="listBox1" HorizontalAlignment="Left" DisplayMemberPath="Name" 
    ItemsSource="{Binding}" Height="134" Width="224" />
<sdk:TreeView Height="132" Name="treeView1" Width="230" 
    ItemsSource="{Binding}" ItemTemplate="{StaticResource WriterTemplate}" />
<sdk:DataGrid AutoGenerateColumns="True" Height="133" Name="dataGrid1" 
    Width="456" ItemsSource="{Binding}"/>
 

The following code-behind shows the Writer business object and collection that the list controls are bound to.

C#

public partial class MainPage : UserControl
{
    public MainPage()
    {
        InitializeComponent();
        ObservableCollection<Writer>
            writers = new ObservableCollection<Writer>() {
            new Writer("Chris Sells", new ObservableCollection<string>()
                {"ComboBox", "ComboBoxItem"}, "Writer II"), 
            new Writer("Luka Albrous", new ObservableCollection<string>()
                {"ListBox","ListBoxItem"}, "Senior Writer"), 
            new Writer("George Louverdis", new ObservableCollection<string>()
                {"DataGrid","Binding"}, "Writer I")
            };
          
        listBox1.DataContext = writers;
        dataGrid1.DataContext = writers;
        treeView1.DataContext = writers;
    }

    public class Writer
    {
        public Writer() { }
        public Writer(string writerName, 
        ObservableCollection listOfTypes, string writerTitle)
        {
            Name = writerName;
            Types = listOfTypes;
            Title = writerTitle;
        }

        public string Name { get; set; }
        public ObservableCollection Types { get; set; }
        public string Title { get; set; }
    }
      
}

Visual Basic

Imports System.Collections.ObjectModel

Partial Public Class MainPage
    Inherits UserControl
    Public Sub New()
        InitializeComponent()
        Dim writers As New ObservableCollection(Of Writer)()
        Dim types As New ObservableCollection(Of String)()
        types.Add("ComboBox")
        types.Add("ComboBoxItem")
        writers.Add(New Writer("Chris Sells", types, "Writer II"))
        types = New ObservableCollection(Of String)()
        types.Add("ListBox")
        types.Add("ListBoxItem")
        writers.Add(New Writer("Luka Albrous", types, "Senior Writer"))
        types = New ObservableCollection(Of String)()
        types.Add("DataGrid")
        types.Add("Binding")
        writers.Add(New Writer("George Louverdis", types, "Writer I"))

        listBox1.DataContext = writers
        dataGrid1.DataContext = writers
        treeView1.DataContext = writers
    End Sub
End Class

Public Class Writer
    Public Sub New()
    End Sub
    Public Sub New(ByVal writerName As String, _
    ByVal listOfTypes As ObservableCollection(Of String), ByVal writerTitle As String)
        Name = writerName
        Types = listOfTypes
        Title = writerTitle
    End Sub

    Private _Name As String
    Public Property Name() As String
        Get
            Return _Name
        End Get
        Set(ByVal value As String)
            _Name = value
        End Set
    End Property
    Private _Types As ObservableCollection(Of String)
    Public Property Types() As ObservableCollection(Of String)
        Get
            Return _Types
        End Get
        Set(ByVal value As ObservableCollection(Of String))
            _Types = value
        End Set
    End Property
    Private _Title As String
    Public Property Title() As String
        Get
            Return _Title
        End Get
        Set(ByVal value As String)
            _Title = value
        End Set
    End Property
End Class

For a complete list of controls by function, see Controls by Function. For more information about the kinds of controls and the content they display, see Control Content Models.

See Also

What's Next

Now that you have an overview of different controls available, let's dig in deeper into working with text in your UI: Text and Rich Text.

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)