Silverlight 101
Silverlight 3 Controls Quick Start Guide
Get acquainted with new layout, input, and items controls in Silverlight 3 Beta
By Dan Wahlin
Controls are where it's at in the world of software development. Whether you're building web, desktop, or mobile applications, controls can minimize the amount of code that has to be written leading to greater overall productivity. Although the initial release of Silverlight lacked any line-of-business controls, Silverlight 3 provides a rich set of controls that can be used to build applications capable of collecting and displaying a variety of data. Here I'll introduce you to some of the controls available in Silverlight 3 Beta and demonstrate how they can be used. I'll provide an overview of layout controls, user-input controls, and items controls. Let's start by examining how to define and use layout controls.
Layout Controls
Layout controls are a key part of Silverlight applications, since they allow other types of controls to be arranged on a UI. Silverlight provides several different controls that you can use, such as Canvas, Grid, StackPanel, and Border. The Canvas control allows controls to be arranged using absolute positioning techniques. For example, to lay out rectangle and square shapes, you could use the following XAML:
Canvas.Top="50"
Canvas.Left="10" RadiusX="10" RadiusY="10" /> Canvas.Top="50"
Canvas.Left="200" /> Both shapes are positioned using the Canvas.Top and
Canvas.Left "attached properties," which positions the respective
shape within the parent Canvas container. In this example, the Rectangle is
positioned 10 pixels in from the left of the Canvas (not from the overall UI)
and 50 pixels from the top of the Canvas, while the Ellipse is positioned 200
pixels from the left and 50 pixels from the top. The Canvas control works great when you need
absolute control over the position of controls, but in many cases it's more
effective to position controls using more of a flow layout, so that they can
adapt to changes in the width and height of the UI. The StackPanel control
provides a great way to "stack" controls vertically or horizontally.
It stacks controls vertically by default, but if you'd like to stack the
controls horizontally, you can set the Orientation property to Horizontal. Following
is an example of using the StackPanel to stack the two shapes shown earlier;
Figure 1 shows an example of what Silverlight renders. Figure 1:
Using the StackPanel controls to stack controls vertically RadiusX="10"
RadiusY="10" /> You can add additional spacing between the controls
by setting their respective Margin property. The margin property allows left,
top, right, and bottom values to be set, as the following example shows: Margin="5,10,5,0"
/> You can also apply a single value to the Margin
property in cases where spacing should be applied equally around all four
sides. This example would add a margin of 10 pixels around all sides of an
Ellipse: In cases where you need more control over layout
precision than the StackPanel provides but don't want to resort to absolute
positioning, you can use the Grid control to lay out controls and data in a
tabular format, much like the standard HTML table element. Figure 2 shows an
example of using the Grid control to arrange a few controls for a simple form.
HorizontalAlignment="Left" VerticalAlignment="Top" Width="150"
Grid.Column="1" />
HorizontalAlignment="Left" VerticalAlignment="Top"
Width="150" Grid.Row="1"
Grid.Column="1" />
HorizontalAlignment="Left"> Figure 2:
Using the Grid control to arrange controls in rows and columns Looking through the code, you'll notice that
controls don't have to be wrapped with row and column tags as in HTML pages.
Instead, columns and rows are defined once, and controls are then placed into
the appropriate row and column using the Grid.Row and Grid.Column attached
properties. The width of the columns is set using a percentage type syntax
where .25* represents 25 percent. The final layout control that can be used is the
Border control. It's a simple control that allows a border to be placed around
a single child control. Having only one child control may sound limiting at
first, but the child control can be another layout control, such as a Canvas,
Grid, or StackPanel that has its own child controls. What makes the Border
control nice to use is its ability to round corners by using the CornerRadius
property and supply solid colors or gradients as backgrounds. Here's an example
of using the border control: BorderThickness="2"
BorderBrush="#cccccc"> Figure 3 shows how the Border control looks when
the Grid shown in Figure 2 is placed inside of it. Figure 3:
Using the Border control and setting the CornerRadius to round corners User-Input Controls Silverlight 3 provides several standard user-input
controls, such as TextBox, RadioButton, CheckBox, and Button. Because these
controls derive from a class called FrameworkElement, they can be transformed
and animated which presents some interesting opportunities, especially when it
comes to data validation. The controls can be bound directly to object
properties, which can simplify development and significantly minimize the
amount of code writing, especially when compared with standard ASP.NET data-binding
techniques. I'll provide more details about binding data to Silverlight
controls in an upcoming article. Defining user-input controls in Silverlight is much
like defining server controls in ASP.NET Web Forms. The main difference is that
you don't prefix the controls with "asp". Instead, you create a XAML
element named after the class. For example, to define a TextBox, you can use
the following XAML code: You can define a Button control just as easily,
although you set the text of the control using the Content property as opposed
to the Text property: Likewise, RadioButton and CheckBox controls can be
defined using their class names. Here's an example of grouping several
RadioButton controls in a StackPanel: Because the controls are in the same parent
container, Silverlight will automatically make them mutually exclusive. If the
controls were in different parent containers, you could use the RadioButton
control's GroupName property to ensure that users can make only one selection.
Simply provide the same value for GroupName on each control. Silverlight's CheckBox control is somewhat unique
as compared with the standard checkbox control used in web pages. Silverlight's
CheckBox can handle three states: checked, unchecked, and indeterminate. This
can be useful when a checkbox is bound to data that can be null (the
indeterminate state). Here's an example of defining a three-state checkbox: It's important to note that the control's
IsThreeState property must be set to true to enable this behavior. Otherwise,
the standard two-state checkbox will be used. Figure 4 shows the different Silverlight
CheckBox states. Figure 4:
Example of three-state Silverlight CheckBox control Items Controls Nearly every data-driven application out
there needs to be able to display collections of items to users. Silverlight 3
provides controls such as ComboBox, ListBox, and DataGrid that allow items to
be displayed in different ways. The ComboBox is similar to ASP.NET's
DropDownList, the ListBox is comparable to the ASP.NET DataList or Repeater
controls, and the DataGrid is similar to the GridView (or the old DataGrid). Following is an example of using the
ComboBox control. This example adds items directly into the control, but they
can also be retrieved from a service and bound dynamically. SelectionChanged="cbStates_SelectionChanged"> When the user selects an item, the
cbStates_SelectionChanged event handler is called, and the selected value is
updated in a TextBlock control, like this: private void cbStates_SelectionChanged(object sender, SelectionChangedEventArgs
e) { this.State.Text = "Selected "
+ ((ComboBoxItem)this.cbStates.SelectedItem).Content; } Data can also be bound to controls such as
ComboBox, ListBox and DataGrid using their ItemsSource property. Once data is
assigned, it's automatically bound, so there's no need to call a DataBind()
method as in ASP.NET. Figure 5 shows an example of a templated ListBox control
and Figure 6 shows how to bind data to the control as a Silverlight application
loads. Width="500"
BorderBrush="Black" BorderThickness="1" FontFamily="Arial"
Margin="10">
Margin="2"
VerticalAlignment="top" Height="35" Width="25"
/> FontSize="14"
Foreground="Navy" />
FontSize="14" Foreground="Red" />
FontSize="14" Foreground="Green" />
Figure 5:
Using the ListBox control to display a collection of items In Figure 6, although the data is coded directly
into the Page_Loaded event handler, it could also be retrieved from a service. void Page_Loaded(object sender, RoutedEventArgs e) { string imagePath = "/Images/blue.png"; List { new
Customer{CustomerID=1,Name="Elaine", Address="1234
Anywhere St.", Phone="123-123-1234",ImageUrl=imagePath}, new
Customer{CustomerID=2,Name="Danny", Address="45
S. Code Way", Phone="555-555-1234",ImageUrl=imagePath}, new
Customer{CustomerID=3,Name="Heedy", Address="45
S. Code Way", Phone="335-123-1234",ImageUrl=imagePath}, }; Customers.ItemsSource =
custs; } Figure 6:
Binding data to the ListBox control The code in Figure 5 uses the ListBox control's
ItemTemplate property to define how each item in the collection should be
displayed. This example uses a Grid control to lay out different controls,
including an Image and three TextBlock controls, as you can see in Figure 7. Figure 7:
Binding data to the Silverlight ListBox control The {Binding PropertyName} syntax seen in the ItemTemplate
represents the declarative data-binding syntax that Silverlight uses to bind a control
to an object property. Although the template syntax is different, if you've
worked with any templated ASP.NET controls before, the overall process should
be familiar. In addition to the ComboBox and ListBox controls,
Silverlight's DataGrid control can also be used to display items. The DataGrid
control has built-in capabilities to sort and edit data, making it a nice
option anytime you're working with tabular data. ASP.NET developers will find
that it's similar to the GridView control (or the old DataGrid control). (For
more information about working with the DataGrid Control, see Bilal Haidar's
"Columns & Rows" article series, running four consecutive months
starting in June 2009.) The easiest way to work with the DataGrid control
is to drag it from the Visual Studio Toolbox into the XAML file. This will
automatically add an XML namespace into the root element of the XAML file that
references an assembly named System.Windows.Controls.Data and a namespace of
System.Windows.Controls, as follows: xmlns:data="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data" To use the DataGrid, you'll need to prefix it with
the appropriate XML namespace prefix (data, in this example). Figure 8 shows an
example of using the DataGrid control. Data can be bound to the control using
the ItemsSource property.
HeadersVisibility="Column"
RowBackground="BlanchedAlmond" AlternatingRowBackground="White"
IsReadOnly="True"
CanUserResizeColumns="True" Margin="10"
HorizontalAlignment="Left"
AutoGenerateColumns="False" Width="300">
Binding="{Binding
Name}" />
Binding="{Binding Address}" />
Binding="{Binding Phone}" />
Figure 8:
Using Silverlight's DataGrid The DataGrid control has three types of columns,
including a check box column, templated column, and text column that can be
used to display data. The example in Figure 8 demonstrates how the
DataGridTextColumn can be used to display name, address, and phone information.
Figure 9 shows how the DataGrid looks once it's rendered. Figure 9:
Using the Silverlight DataGrid control to display information A Starting Point Although this article has only scratched the
surface when it comes to Silverlight 3 controls, you've seen how XAML can be
used to define controls and how a few of the controls can be used. In the next
few articles, I'll be providing additional information about binding data to
controls and examining additional controls, such as the new DataForm control. Dan Wahlin, a Microsoft MVP for ASP.NET and XML web services, founded the XML for ASP.NET Developers website and The Wahlin Group (http://www.TheWahlinGroup.com),
which specializes in .NET, Silverlight, and SharePoint consulting and training solutions. Code
accompanying this article is available for download.