Silverlight 2.0 In Examples: Part 1. Silverlight Elements: Panels and Controls

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 object). 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 the following site.

Both Panels and Controls derive from FrameworkElement class.
The figure below desplays a class Hierarchy for Panels and Controls.

ContentControls have 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. Example of ItemControl is ListBox.

Controls

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

Button

Button is a ContentControl whose primary goal is to trigger some business logic when it is clicked. After the click, the usual 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: buttonsamplezip.doc. As always, remove the doc extension and rename it to ButtonSample.zip.

Here is the screen for the project:

Button Sample

Button Sample

Every time you click this button, the 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 modify 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 Page.xaml file:

<UserControl x:Class=”ButtonSample.Page”

    xmlns=”http://schemas.microsoft.com/winfx/2006/xaml/presentation&#8221;

    xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml&#8221;

    Width=”400″ Height=”300″>

    <Grid x:Name=”LayoutRoot” Background=”White”>

        <Button

            x:Name=”MyButton”

            Width=”150″

            Height=”25″

            Content=”Clicked 0 Times”/>

    </Grid>

</UserControl>

One 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

{

    intnumClicks = 0;

 

    public Page()

    {

        InitializeComponent();

        MyButton.Click += new RoutedEventHandler(MyButton_Click);

    }

 

    voidMyButton_Click(object sender, RoutedEventArgs e)

    {

        numClicks++;

 

        MyButton.Content = “Clicked “+ numClicks + ” times.”;

    }

}

 

Take a look at Page() constructor. One 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 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 MyButton_Click function:

 

    voidMyButton_Click(object sender, RoutedEventArgs e)

    {

        numClicks++;

 

        MyButton.Content = “Clicked “+ numClicks + ” times.”;

    }

 

DatePicker

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 DatePicker sample: datepickersamplezip.doc.
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:

Date Picker Sample

Date Picker Sample

Note, that in order to make DatePickerSample compile, we had to add 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 System.Windows.Controls namespace of System.Windows.Controls.Extended assembly.
Later within the XAML code, we can find DatePicker control by adding “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 SelectedDate property of the DatePicker:

DateTime? selectedDate = MyDatePicker.SelectedDate;

 

if(selectedDate != null)

    MyButton.Content = ((DateTime)selectedDate).ToString();

ListBox Control

ListBox is an ItemsControl. Its purpose is to display multiple items as a list. It can have one of the items selected. Here is a very simple example: listboxsamplezip.doc (more complicated examples with binding will be presented in subsequent parts of this tutorial).

ListBox Sample

ListBox Sample

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 ListBox containing multiple ListBoxItems. The selected item is referenced by the SelectedItem property of the ListBox.

Other Controls

As one can see from Demo Controls there are many other important controls. Since currently 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 – 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 – deserve 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

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: canvassamplezip.doc.
The figure below, shows a button positioned on top of a Canvas, 200 generic pixels down and 100 to the right.

Canvas Sample

Canvas Sample

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

StackPanel allows to put visual objects one after another vertically or horizontally. One can only space out the objects one from another by using their Margin property. Margin consists of 4 numbers specifying in the same order the distance from the left, from the top and the extra space before next element from the right and from the bottom.
Here is the source code for StackPanel example: stackpanelsamplezip.doc.
The following figure shows the screen for the sample:

Stack Panel Sample

Stack Panel Sample

The sample includes 2 StackPanels: Vertical and Horizontal. 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>

One can see that the top level StackPanel has Vertical (default) orientation and contains two buttons and another StackPanel as children. With the help of 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 2 buttons spaced horizontally by 10 generic pixels.

Grid

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 height and the columns can have different width.
Here is a code sample for the Grid: gridsamplezip.doc.
When run, this sample produces the following window:

Grid Sample

Grid Sample

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 RowDefinition and ColumnDefinition tags correspondingly. The item can be placed to a certain cell by defining Grid.Row and Grid.Column properties. Within each cell, the item position is controlled by HorizontalAlignment and VerticalAlignment properties. In addition, one can use 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.

Advertisements

Tags: , ,

2 Responses to “Silverlight 2.0 In Examples: Part 1. Silverlight Elements: Panels and Controls”

  1. Silverlight 2.0 In Examples: Part ? Drag and Drop Inside Out « Nick Polyak’s Software Blog Says:

    […] This is a continuation of a tutorial, see Silverlight 2.0 In Examples: Part 0. Introduction” and “Silverlight 2.0 In Examples: Part 1. Silverlight Elements: Panels and Controls. […]

  2. Alexwebmaster Says:

    Hello webmaster
    I would like to share with you a link to your site
    write me here preonrelt@mail.ru

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


%d bloggers like this: