Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Silverlight 2.0 in Examples: Part 1 - Silverlight Elements: Panels and Controls

0.00/5 (No votes)
24 Sep 2008 1  
part 1 of silverlight 2.0 tutorial

Introduction

This is part 1 of the tutorial, but there is also Part 0. You can access it through the following link: Part 0. Part 0 of the tutorial was at an introductory level. Here, we will switch to the more advanced concepts. In particular, we will assume that the readers are familiar with C# and most of the OO concepts it uses, e.g., inheritance. We will also assume that the readers have some basic knowledge of Visual Studio 2008.

This installment will include multiple simple examples showing how to use Silverlight elements: panels and controls, while, at the same time, displaying the ways Silverlight works.

Overview of Panels and Controls

Silverlight 2.0 comes with many built-in objects ready to be used for building a business logic application. Such objects are sub-divided into Panels and Controls. Panels are GUI objects that contain other GUI objects (their children objects). Practically, any visual object can be placed within a panel: other panels, controls, etc. A panel's main purpose is to position its child objects. Controls usually serve to trigger some business logic behavior of an application or to provide (and change) some business logic values.

For a comprehensive demo with Silverlight 2.0 Beta 2 controls, check this site.

Both Panels and Controls derive from the FrameworkElement class. The figure below displays a class hierarchy for Panels and Controls.

SilverlightObjectsInheritanceDiagram.JPG

ContentControls has a property "Content" that can be used to contain other controls (not quite true yet for Silverlight 2.0 Beta). ItemsControls are used to display collections of objects. An example of an ItemControl is a ListBox.

Controls

In this section, we are going to consider individual Control examples.

Button

The Button is a ContentControl whose primary goal is to trigger some business logic when it is clicked. After the click, the button comes back to the original state and becomes ready for the next click.

Here is the source code for a simple project emphasizing the way Buttons work:

Here is the screen for the project:

ButtonProject.jpg

Every time you click this button, the displayed number of clicks increases. Now, let us discuss the code. As was mentioned in Part 0 of this tutorial, most of the time, we do not need to modify the App.xaml and App.xaml.cs files. So, let us take a look at the Page.xaml and Page.xaml.cs files within the solution.

Here are the contents of the Page.xaml file:

<UserControl x:Class="ButtonSample.Page"
   xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    Width="400" Height="300">
    <Grid x:Name="LayoutRoot" Background="White">
        <Button 
            x:Name="MyButton"
            Width="150"
            Height="25"
            Content="Clicked 0 Times"/>
    </Grid>
</UserControl>

We can see a simple button within a grid. The button has a name (x:Name="MyButton"). Name is used for accessing this control or element from the C# code (we'll talk more about it below). It also has its Width, Height, and Content properties set. You can play with the button by changing or removing the properties and watching the way the button changes. Now, let us take a look at the C# code within the Page.xaml.cs file. Here are its contents:

public partial class Page : UserControl
{
    int numClicks = 0;

    public Page()
    {
        InitializeComponent();
        MyButton.Click += new RoutedEventHandler(MyButton_Click);
    }

    void MyButton_Click(object sender, RoutedEventArgs e)
    {
        numClicks++;

        MyButton.Content = "Clicked " + numClicks + " times.";
    }
}

Take a look at the Page() constructor. We can notice that within that constructor, we refer to MyButton as if it was a member of the class. Well, in fact, it is a member of the class; we've made it so, by naming it "MyButton" within the XAML code. Now, all we have to do is to specify the desired behavior when the button is clicked. This is achieved by adding a handler to the "Click" event:

MyButton.Click += new RoutedEventHandler(MyButton_Click);

and by creating the body of the handler as a MyButton_Click function:

void MyButton_Click(object sender, RoutedEventArgs e)
{
    numClicks++;
    MyButton.Content = “Clicked “+ numClicks + ” times.”;
}

DatePicker

The DatePicker is a control that allows to choose a date. The chosen date is specified by the SelectedDate property of the DatePicker. Here is the source code for a DatePicker sample:

The sample allows the user to choose the date using the DatePicker. Then, whenever the button at the bottom is clicked, the content of the button is changed to the picked date:

DatePickerSample.jpg

Note, that in order to make DatePicker sample compile, we had to add the System.Windows.Controls.Extended assembly to the project's references. This is also reflected within the Page.xaml file, by the following line:

xmlns:extended="clr-namespace:System.Windows.Controls;
                assembly=System.Windows.Controls.Extended"

This line makes "extended" to be the XAML namespace for the functionality located within the System.Windows.Controls namespace of the System.Windows.Controls.Extended assembly. Later, within the XAML code, we can find the DatePicker control by adding the "extended:" prefix to it:

<extended:DatePicker
    x:Name=”MyDatePicker”
    HorizontalAlignment=”Center”
    VerticalAlignment=”Center”>
</extended:DatePicker>

Finally, if we look at the C# code, we notice that the Content property of the Button is set to the SelectedDate property of the DatePicker:

ListBox

The ListBox is an ItemsControl. Its purpose is to display multiple items as a list. It can have one of its items selected. Here is a very simple example:

(More complicated examples with binding will be presented in subsequent parts of this tutorial.)

ListBoxSample.jpg

Here is the interesting part of the Page.xaml file:

<ListBox Width=”100″ Height=”100″>
    <ListBoxItem Content=”Item1″/>
    <ListBoxItem Content=”Item2″/>
    <ListBoxItem Content=”Item3″/>
</ListBox>

You can see the ListBox containing multiple ListBoxItems. The selected item is referenced by the SelectedItem property of the ListBox.

Demo Controls

There are many other important controls. Since I do not have time to provide examples for them all, I am going to briefly describe some of them in this section:

  • Border - Purely visual control without any specific behaviors. It provides the visual presentation for the border of its content.
  • CheckBox - A control with two states: "clicked" and "not clicked". Its boolean property IsClicked reflects its state.
  • GridSplitter - Allows resizing the rows or the columns within the GridPanel.
  • RadioButton - Allows to create groups of mutually exclusive check buttons: if one is in the pressed state, the others are not.
  • Slider - A slider control. Its Value property specifies how far the slider moved.
  • TextBlock - Just a way to present the text that cannot be edited by the user. The text string is stored in its Text property.
  • TextBox - Represents editable text. The text string is reflected by its Text property.
  • DataGrid - Deserves a special section all to itself. Allows presenting data in table format.
  • TabControl - Allows presenting multiple screens as tabs within the same window.
  • ToolTip - Associates a popup message with any control. This message is displayed whenever the mouse is on top of the control.

Panels

As was mentioned before, panels are containers of Silverlight visual objects that have a say over where and how the objects are positioned.

Canvas

The Canvas is a panel that positions its child objects by the coordinates (how much to the right the object is from the left end of the panel, and how much down it is from the top). The sample code can be downloaded from here:

The figure below shows a Button positioned on top of a Canvas, 200 generic pixels down and 100 to the right.

CanvasSample.jpg

The corresponding XAML code is the following:

<Canvas x:Name=”LayoutRoot” Background=”White”>
    <Button 
        Canvas.Left=”100″ 
        Canvas.Top=”200″
        Content=”Hello World”/>
</Canvas>

As you can see, the property Canvas.Left sets the position of the button horizontally, and Canvas.Top - vertically.

StackPanel

The StackPanel allows to put visual objects one after another, vertically or horizontally. We can only space out the objects one from another by using their Margin property. Margin consists of 4 numbers specified in the same order as the distance from the left, from the top, and the extra space before the next element from the right and from the bottom. Here is the source code for a StackPanel example:

The following figure shows the screen for the sample:

StackPanelSample.jpg

The sample includes two StackPanels: Vertical and Horizontal. The horizontal StackPanel is placed inside the vertical one. Here is the corresponding XAML:

<StackPanel
    x:Name=”LayoutRoot” 
    Background=”White”>
    <Button 
        Width=”200″
        Height=”25″
        Margin=”0,10,0,0″
        Content=”Vertical Button 1″/>
    <Button 
        Width=”200″
        Height=”25″
        Margin=”0,10,0,0″
        Content=”Vertical Button 2″/>
    <StackPanel 
        Margin=”0,10,0,0″
        Orientation=”Horizontal”>
        <Button 
            Width=”150″
            Height=”25″
            Margin=”10,0,0,0″
            Content=”Horizontal Button 1″/>
        <Button 
            Width=”150″
            Height=”25″
            Margin=”10,0,0,0″
            Content=”Horizontal Button 2″/>
    </StackPanel>
</StackPanel>

We can see that the top level StackPanel has a vertical (default) orientation and contains of two Buttons and another StackPanel as children. With the help of the Margin property, the Buttons and the child StackPanel are spaced vertically 10 generic pixels apart. The child StackPanel has horizontal orientation (controlled by the property "Orientation") and contains two buttons spaced horizontally by 10 generic pixels.

Grid

The Grid allows to split the area it occupies into rows and columns. There can be different number of rows and columns; the rows can have different heights, and the columns can have different widths. Here is a code sample for the Grid:

When run, this sample produces the following window:

GridSample.jpg

Let us take a look at the XAML:

<Grid x:Name=”LayoutRoot” Background=”White”>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width=”80″/>
        <ColumnDefinition Width=”80″/>
    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
        <RowDefinition Height=”55″/>
        <RowDefinition Height=”55″/>
    </Grid.RowDefinitions>
    <TextBlock 
        Grid.Row=”0″
        Grid.Column=”0″
        Text=”Cell (0, 0)”/>        
    <TextBlock 
        Grid.Row=”0″
        Grid.Column=”1″
        HorizontalAlignment=”Right”
        Text=”Cell (1, 0)”/>
    <TextBlock 
        Grid.Row=”1″
        Grid.Column=”0″
        Text=”Cell (0, 1)”/>
    <TextBlock 
        Grid.Row=”1″
        Grid.Column=”1″
        VerticalAlignment=”Bottom”
        Text=”Cell (1, 1)”/>
</Grid>

The rows and columns are defined by the RowDefinition and ColumnDefinition tags, respectively. The item can be placed to a certain cell by defining the Grid.Row and Grid.Column properties. Within each cell, the item position is controlled by the HorizontalAlignment and VerticalAlignment properties. In addition, we can use the Margin property to position an element within each cell.

Conclusion

In this part of the tutorial, we presented several Silverlight Controls and Panels, which are the building blocks of business logic applications. Later, we are going to use them to create some cooler stuff.

Please rate this article if you like it

If you don't, please, give me suggestions for writing better articles. Thanks.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here