In the previous article I described how to create a simple Silverlight application in Microsoft Visual Studio 2010. In this article I will describe what are the different Layout Management Panels in Silverlight and how and when they are used. When you create a Silverlight project using Visual Studio, it creates a default XAML file called "MainPage.xaml". This is just a dummy start page created by Visual Studio and it does not contain any visible UI elements. The default content of the MainPage.xaml file looks like this:
mc:Ignorable="d" d:DesignWidth="640" d:DesignHeight="480">
The above code shows a user control and a Grid control. The UserControl is a high level control that holds all other UI elements in a XAML file. The Grid control is used as a layout panel and it can hold other UI elements. All UI elements in a .XAML control must be placed within a layout panel. There are 3 different types of layout panels available in Silverlight.
- Grid Panel
- Stack Panel
- Canvas Panel
Each of these methodologies fit in to different situations as per layout needs. All these layout controls inherit from Panel class.
Grid layout helps you position your controls using rows and columns. It’s very similar to table defined in HTML.
Above we created a simple table with two columns and two rows. Using Grid.ColumnDefinitions we defined two columns and using Grid.RowDefinitions we defined two rows. Then We created 4 text blocks which are then specified in each section using Grid.Column and Grid.Row. For instance to place in the first column we need specify the Grid.Column as “0”and Grid.Row as “0”.
Stack allows you to arrange/group UI elements vertically or horizontally. Controls do not overlap. For instance below are 4 elements which are arranged in a stack panel element. You can see how the stack aligns / stacks the elements one above other. You can also stack the UI elements horizontally or vertically depending on your layout nature.
By default Orientation is Vertical. You can arrange controls horizontally by using Orientation = Horizontal. You can use Margin Property to change the location on control inside the stack panel. See below
Canvas is the simplest methodology for layout management. It supports absolute positioning using ‘X’ and ‘Y’ coordinates. Canvas.Left helps to specify the X co-ordinate while Canvas.Top helps to provide the ‘Y’ coordinates.
You can think Canvas as a HTML div Tag, where you can put your content in specific location by providing absolute left and top position.
If you are familiar with Photoshop, Photoshop creates layers to position them on top of each other. Canvas.ZIndex property of controls does the same. Greater the ZIndex control will appear on the top.