Thursday, December 23, 2010

A Simplified Grid Markup for Silverlight and WPF

The WPF / Silverlight syntax is long and cumbersome. This blog post describe a simple attached property that allows you to specify row and column widths / heights as a simple comma separated list, e.g. RowDefinitions=”Auto,,3*,,,,2*”
The Grid is probably one of the most useful and versatile layouts that Silverlight and WPF offers. However, if you hand craft your XAML, as I do, you will probably start to find the Grid markup for defining rows and columns to be verbose and cumbersome. If we look at the following example, which uses a mixture of Auto, Star and Pixel widths / heights:

<Grid>
 <Grid.RowDefinitions>
   <RowDefinition Height="Auto"/>
   <RowDefinition/>
   <RowDefinition/>
   <RowDefinition/>
   <RowDefinition/>
   <RowDefinition/>
   <RowDefinition Height="2*"/>
 </Grid.RowDefinitions>
 <Grid.ColumnDefinitions>
   <ColumnDefinition Width="100"/>
   <ColumnDefinition/>
 </Grid.ColumnDefinitions>
 <TextBlock Text="User Details" FontSize="20"
         HorizontalAlignment="Center"
         Grid.ColumnSpan="2"/>
 <TextBlock Text="Forename:"
             Grid.Row="1"/>
 <TextBox Text="Jeremy"
           Grid.Column="1" Grid.Row="1"/>
 <TextBlock Text="Surname:"
             Grid.Row="2"/>
 <TextBox Text="James"
           Grid.Column="1" Grid.Row="2"/>
 <TextBlock Text="Age:"
             Grid.Row="3"/>

Read more: Scott Logic