Silverlight Tutorial Part 2: Using Layout Management

This is part two of eight tutorials that walk through how to build a simple Digg client application using the Beta1 release of Silverlight 2.  These tutorials are intended to be read in-order, and help explain some of the core programming concepts of Silverlight.  Bookmark my Silverlight 2 Reference page for more of Silverlight posts and content. 

<Download Code> Click here to download a completed version of this Digg client sample. </Download Code>

Understanding Layout Management

Silverlight and WPF support a flexible layout management system that enables developers and designers to easily coordinate how controls are positioned within a UI surface.  This layout system supports both a fixed position model where controls are positioned using explicit coordinates, as well as a more dynamic position model where layout and controls can be automatically sized and flowed as the browser resizes.

Developers using Silverlight and WPF use layout panels to coordinate the position and resizing of controls contained within them.  The built-in layout panels in Silverlight Beta1 include three of the most commonly used ones in WPF:

  • Canvas
  • StackPanel
  • Grid

Canvas Panel

The Canvas panel is a pretty basic layout panel that supports positioning controls contained within it using explicit coordinates.

You position elements in a Canvas using a XAML feature called "Attached Properties" - which allow you to specify a control's position relative to its immediate parent Canvas control's Left, Top, Right or Bottom coordinates.  Attached properties are useful as they allow a parent panel to extend the property set of a control contained within it. Canvas, by defining an attached property for “Top” and ”Left” basically adds the ability to define left and top attachment on Button (or any other UI element that is added to the Canvas), without any need to actually add a property to the Button class, or modify the Button class in any way.

We could add two buttons to a Canvas container, and position them both 50 pixels from the left of the Canvas, and 50 and 150 pixels from the top using XAML like below (the Canvas.Left and Canvas.Top attributes are examples of the attached property syntax):

This would then render our buttons like below:

While the Canvas is useful for scenarios where the UI elements contained within it never move, it tends not to be very flexible as you add more controls into it or handle scenarios where the UI needs to resize or move.  In cases like these you end up having to manually write code yourself to move things around inside the Canvas (which is a pain).  A better solution for these dynamic scenarios is typically to use an alternative layout panel that has built-in semantics to-do this for you - like the StackPanel and Grid.

StackPanel

The StackPanel control is a simple layout panel that supports positioning its contained controls in either a row or column layout.  StackPanels are typically used in scenarios where you want to arrange a small subsection of the UI on your page.

For example, we could use the StackPanel to vertically arrange three buttons on our page using XAML markup like below:

At runtime the StackPanel would then automatically arrange the Button controls in a vertical stack for us like below:

We could alternatively set the "Orientation" property of the StackPanel to be "Horizontal" instead of Vertical (which is the default):

This will then cause the StackPanel to automatically arrange the Button controls in a horizontal row like below:

Grid Panel

The Grid control is the most flexible layout panel, and supports arranging controls in multi-row and multi-column layouts.  It is conceptually similar to an HTML Table element.

Unlike an HTML Table, you don't embed controls within column and row elements.  Instead you specify a Grid's Row and Column definitions using <Grid.RowDefinitions> and <Grid.ColumnDefinitions> properties that are declared immediately under the <Grid> control.  You can then use the XAML "Attached Property" syntax on controls contained within the grid to indicate which Grid row and column they should be populated within.

For example, we could declare a Grid layout has three rows and three columns, and then position 4 buttons within it using XAML like below:

The Grid layout panel would then position the Button elements for us like so:

In addition to supporting absolute sizing (for example: Height="60") the Grid's RowDefinition and ColumnDefinition controls also support an AutoSizing mode (Height="Auto"), which automatically sizes the Grid or Row based on the size of the content contained within it (you can also optionally specify maximum and minimum size constraints - which can be very useful).

The Grid's Row and ColumnDefinitions also support a feature called "Proportional Sizing" - which enables the size of a Grid's Rows and Columns to be spaced proportionally relative to each other (for example: you could have the second row grow at 2x the rate of the first one).

You'll find that the Grid provides a ton of power and flexibility - and it will probably be the most common layout panel control you'll end up using.

Using Layout Panels to Arrange our Digg Page

Remember that the goal when building our Digg sample is to create a page that looks like the one below:

To create this layout we'll begin by adding a root Grid panel that has two RowDefinitions within it.  The first Row will be 40 pixels high, and the second will fill the remaining space (Height="*"):

Tip: Notice above how I've set the Grid's "ShowGridLines" property to "True".  This will enable us to easily visualize the Row and Column boundaries within the Grid when we test it at runtime:

We'll then embed a second Grid panel control as a child control within the first row of the root Grid panel container, and use it to arrange the top row (the header).  We'll create three columns within it - one for the Title, one for the Search TextBox, and one for the Search Button:

Once this is done we have the basic layout arrangement of our Digg search page in place:

Note: As an alternative to nesting Grids, we could have alternatively had one Grid with 3 columns and 2 rows and used the ColSpan/RowSpan feature of the Grid to merge content across multiple columns (similar to how you can do this with HTML tables).  I chose to use the nested Grid approach instead because I thought it would be simpler to follow along.

Now that we have the layout setup all we need to-do is add controls to it. 

For the header row we'll use the built-in <Border> control (with a CornerRadius of 10 to get a nice rounded edge) and add some text inside it to create the Title.  We'll use the built-in <WatermarkedTextBox> control in the second column for the search textbox.  And we'll put a search <Button> in the third column.  We'll then put some placeholder text in the second row where we are later going to display the search results.

Note: Below I'm embedding style information (FontSize, Colors, Margins, etc) directly on the controls.  Later in this tutorial series I'll show how to use Styles to extract and encapsulate these settings in a separate file (ala CSS) which can then be re-used across the application. 

 

And now when we run our application it looks like below:

Dynamically Resizing our Application

One thing you might have noticed in the XAML above is that our top-level control is currently set to be a fixed width and height:

When set this way our Silverlight Application will always remain that fixed size.  Expand the browser and this becomes apparent:

While constraining an embedded application to be a fixed size within a region of an HTML page is useful in some scenarios, for our Digg search application we really want the application experience to automatically flow and resize with the browser - just like an HTML page would.

The good news is that this is easy to implement.  Just remove the Width and Height attributes on the root control:

Our Silverlight application will then automatically expand (or shrink) to fill the HTML container it is embedded within.  Because the SilverlightTestPage.html file that we are testing our Silverlight application within hosts our Silverlight control in a HTML <div> element with a 100% width and height CSS setting on it, our Digg application will now fill the entire browser:

Notice how the content within the header of the application automatically resizes and flows based on the width of the browser:

When we shrink the browser, the watermark textbox and search button stay the same size because their Grid container columns are a fixed width.  The <Border> control containing our "Digg Search" title automatically resizes when we shrink the browser because the Grid column it is in is configured to be Width="*".

We did not need to write a single line of code to enable this layout behavior - the Grid container and the layout system took care of dynamically resizing and flowing everything for us.

Next Steps

We now have the basic layout structure of our Digg application created, and have our header row defined.

Our next step will be to implement the searching behavior of the application - and have it actually retrieve story content from Digg.com when an end-user using the application searches on a topic.

To-do that let's jump to our next tutorial: Using Networking to Retrieve Data and Populate a DataGrid.

Published Friday, February 22, 2008 5:55 AM by ScottGu

Comments

# First Look at Silverlight 2

Friday, February 22, 2008 10:22 AM by Community Blogs

Last September we shipped Silverlight 1.0 for Mac and Windows , and announced our plans to deliver Silverlight

# re: Silverlight Tutorial Part 2: Using Layout Management

Friday, February 22, 2008 11:27 AM by Michael Sync

1. 100% in CSS become * in Silverlight, isn't it? How come you guys got the idea to give * instead of 100% that we used to do for so many years.

2. Canvas layout is the same as old one?

3. In Grid, Is it possible to define the width or height of the first column instead of setting each and every columns? (like HTML table, we only need to specify the width and height of the first cell of table..  )

# Getting Read for Silverlight 2.0

Friday, February 22, 2008 12:06 PM by ASPInsiders

Scott Guthrie just released new information about Silverlight 2.0 including 8 tutorials.&#160; It's going

# re: Silverlight Tutorial Part 2: Using Layout Management

Friday, February 22, 2008 3:58 PM by Ken

Michael ---

Silverlight is not a subset of CSS, it is a subset of WPF and the .Net Framework.  The * has always been used when creating XAML for WPF.

--- Ken

# Scott Guthrie lève le voile sur Silverlight 2

Friday, February 22, 2008 6:54 PM by ASP.NET Français Blogs

A une semaine de l&#39;ouverture de la conférence Mix08 de Las Vegas, Scott Guthrie - Corporate Vice

# re: Silverlight Tutorial Part 2: Using Layout Management

Saturday, February 23, 2008 2:12 PM by Michael Sync

>>Silverlight is not a subset of CSS, it is a subset of WPF and the .Net Framework.  The * has always been used when creating XAML for WPF.

Yes. I know.. but still .. why not 100% in XAML? :)

# re: Silverlight Tutorial Part 2: Using Layout Management

Saturday, February 23, 2008 5:03 PM by Johannes Hansen

Michael Sync.

WPF doesn't operate with a % syntax instead it uses the "star" syntax. The * just means take up the remaining space available, it has nothing to do with percentages. Furthermore if several stars exists they should share the remaining space. For example:

<ColumnDefinition Width="*" />

<ColumnDefinition Width="*" />

<ColumnDefinition Width="100" />

Would mean that if the total width of the grid is 300, each row will get 100 or 33% of the space. However you can weight each * so it gets a weighted amount of the remaining space... For example:

<ColumnDefinition Width="*" />

<ColumnDefinition Width="3*" />

<ColumnDefinition Width="100" />

Would leave the first column with 50, the second column with 150 and the third column still gets exactly 100. So you see the star syntax is much more well defined than the css percentage syntax and they can't really be compared.

# re: Silverlight Tutorial Part 2: Using Layout Management

Sunday, February 24, 2008 8:53 AM by Marlon Grech

wow silverlight will be super cool.... can't wait to start blogging on it :D

# A First Look at Silverlight 2.0

Sunday, February 24, 2008 5:33 PM by Techniques

Over at Scott Gutherie's Blog , he has released a series of first articles (and code samples) on Silverlight

# Silverlight Tutorial Part 1: Creating "Hello World" with Silverlight 2 and VS 2008

Sunday, February 24, 2008 6:44 PM by ScottGu's Blog

This is part one of eight tutorials that walk through how to build a simple Digg client application using

# re: Silverlight Tutorial Part 2: Using Layout Management

Sunday, February 24, 2008 11:20 PM by ScottGu

Johannes - Thanks a bunch for helping answer the questions above!  I really appreciate it.

Scott

# re: Silverlight Tutorial Part 2: Using Layout Management

Monday, February 25, 2008 4:34 AM by rohan

I have a general question on a full-blown silver light app. What are the chances of a search engine to be able to crawl on the content (text , other than the meta tags associated with the aspx markup ) hosted in silver a light container.

# re: Silverlight Tutorial Part 2: Using Layout Management

Monday, February 25, 2008 4:55 PM by Bryan Reynolds

Will silverlight work on the IPhone?

# Excelentes Tutoriales para Silverlight 2

Tuesday, February 26, 2008 2:55 PM by Tecnologías Microsoft

Scott nos brinda 8 tutoriales para el desarrollo con silverlight 2 y visual studio 2008 una aplicaci&#243;n

# re: Silverlight Tutorial Part 2: Using Layout Management

Wednesday, February 27, 2008 1:35 AM by ScottGu

Hi Bryan,

>>>>>> Will silverlight work on the IPhone?

Silverlight will work on phones and mobile devices.  The iPhone SDK isn't out just yet.  Once it is we'll be investigating it.

Thanks,

Scott

# First Look at Using Expression Blend with Silverlight 2

Friday, February 29, 2008 2:59 AM by Blogs

Last week I did a First Look at Silverlight 2 post that talked about the upcoming Silverlight 2 Beta1

# re: Silverlight Tutorial Part 2: Using Layout Management

Friday, February 29, 2008 9:17 PM by Rick Anderson

For all those who want to copy/paste follow along and don't have an OCR copy/paste tool:

<UserControl x:Class="DiggSample.Page"

   xmlns="schemas.microsoft.com/.../2007"

   xmlns:x="schemas.microsoft.com/.../xaml"

  >

   <Grid Background="#FF5C7590" ShowGridLines="True">

       <Grid.RowDefinitions>

           <RowDefinition Height="40" />

           <RowDefinition Height="*" />

       </Grid.RowDefinitions>

       <Grid Grid.Row="0" Margin="7" ShowGridLines="True" >

           <Grid.ColumnDefinitions>

               <ColumnDefinition Width="*" />

               <ColumnDefinition Width="200" />

               <ColumnDefinition Width="50" />

           </Grid.ColumnDefinitions>

           <Border Grid.Column="0" CornerRadius="10" Background="#FFDEDEDE" Margin="0,0,5,0">

               <TextBlock Text="DIGG SEARCH" Foreground="#FF14517B" Margin="10,3,0,0" />

           </Border>

           <WatermarkedTextBox Grid.Column="1" FontSize="14" Watermark="Topic..." />

           <Button Grid.Column="2" Content="Search" />

       </Grid>

       <TextBlock Grid.Row="1" Margin="10" Foreground="White" >

           Todo: Stories will display here....

       </TextBlock>

   </Grid>

</UserControl>

  <!--For bonus points use FF for a few screen shots (Like how you use google and MSN search)   A++ work, very helpful -->

# re: Silverlight Tutorial Part 2: Using Layout Management

Saturday, March 01, 2008 12:12 PM by James

Very interested in your series and the questions arise after! SilverLight will rock... I came across this site (http://tafiti.mslivelabs.com/) and truely like the interface(s).

-JD

# Silverlight チュートリアル パート 2: レイアウト管理の使用

Sunday, March 02, 2008 12:16 AM by Chica's Blog

Silverlight チュートリアル パート 2: レイアウト管理の使用

# re: Silverlight Tutorial Part 2: Using Layout Management

Wednesday, March 05, 2008 9:16 AM by Marco

The missing layout component on Silverlight 1.0 was a showstopper for me. I'm glad you guys made this available in the 2.0 release. I can start finishing of my RIA rule editing.

# Silverlight 2.0 Video Tutorials

Wednesday, March 05, 2008 11:04 AM by Community Blogs

Silverlight 2.0 provides a new and exciting framework for building rich applications using C#, VB.NET

# re: Silverlight Tutorial Part 2: Using Layout Management

Thursday, March 06, 2008 4:45 PM by Joey

The coolest stuff I have seen in a really long time.

# SilverLight 2.0 Tutorials by Scott Guthrie

Friday, March 07, 2008 1:29 AM by Bilal Haidar [MVP, MCT]

Scott Guthrie added a series of tutorials on Silverlight 2.0. You can find them here: Part 1: Creating

# Silverlight 2.0 Video Tutorials (Updated)

Saturday, March 08, 2008 2:46 AM by ASPInsiders

Silverlight 2.0 provides a new and exciting framework for building rich applications using C#, VB.NET

# re: Silverlight Tutorial Part 2: Using Layout Management

Wednesday, March 12, 2008 12:46 AM by Mario

Hi Scott, the url "Silverlight 2 Reference page" doesn't seem to be working on this page...

# Silverlight 1.0のレイアウトは正直きつい

Monday, March 17, 2008 10:29 AM by kwLog

さて、Cocoa TouchやAndoridもやらないといけないんですが、そろそろSilverlightやAIRでアプリを作ろうと思い、ちょこちょこ調べていました。 まずはmRadioをSilverl...

# Tutorial Silverlight Parte 2: Administraci??n de Layout &laquo; Thinking in .NET

Pingback from  Tutorial Silverlight Parte 2: Administraci??n de Layout &laquo; Thinking in .NET

# re: Silverlight Tutorial Part 2: Using Layout Management

Tuesday, March 18, 2008 8:05 AM by Juan María

Hi all:

You can read this post in spanish here:

thinkingindotnet.wordpress.com/.../tutorial-silverlight-parte-2-administracion-de-layout

# re: Silverlight Tutorial Part 2: Using Layout Management

Thursday, March 20, 2008 5:12 AM by monir

Why property editing is not available during the edit in XAML file, it usful to learn what property we have?

# Silverlight 2学习笔记二一:三个基本布局控件(Canvas、StackPanel、Grid )

Monday, March 24, 2008 12:44 PM by jailu

这篇文章主要是翻译了ScottGu博客的文章:SilverlightTutorialPart2:UsingLayoutManagement。虽然是翻译,但通过笔记记录,我发现对这三个布局控...

# re: Silverlight Tutorial Part 2: Using Layout Management

Thursday, March 27, 2008 8:48 AM by vishnu

can silverlight be used for applications on Windows CE?

# Expression Blend Tip: Modifying the Rows or Columns of a Grid

Monday, April 07, 2008 5:27 PM by ASPInsiders

It took me a couple of minutes to realize that RowDefinitions and ColumnDefinitions of a Grid are in

# [SilverLight] Primer Look de SilverLight 2.0

Monday, April 07, 2008 8:44 PM by AlexJimenez

El pasado Septiembre publicamos Silverlight 1.0 para Mac y Windows, y anunciamos los planes para Silverlight