Posts Tagged Automatic Grid

Automatic Grid Layout for Silverlight


Download

I always find myself cursing Grids in Silverlight when I have to go back and insert something else into the layout after the fact: I always forget to move somethings Row and end up with a lot of obscured components. To compensate for this I’ve written a Grid subclass that can automatically layout its children and fill out the ColumnDefinition and RowDefinition for missing values when the children refer to rows and columns beyond the specified dimensions. In addition it will auto layout for multiple columns using sequential children, this is good if all you want is a 2 by n grid of label/editor cells.

My AutoGrid will allow you to define Rows and Columns like an ordinary grid, but if you don’t catch all of the cases then it fills out the rest for you. For instance you could just define the columns and it will fill out the rows based on the Grid.Row settings of the children. If you want to go a step further, then don’t specify any Grid.Row or Grid.Column attributes and instead add a Columns=”x” to the AutoGrid and it will sequentially lay out the children in column then row order. 

Normally the rows and columns added are “Auto” sized, you can however set the last row and column to be “*” sized using the properties AutoSizeLastColumn and AutoSizeLastRow.  If you need more complex arrangements than this then you should define the items you need sizing explicity using the ColumnDefinitions and/or RowDefinitions attributes.

It really saves me a lot of time when I’m editing this stuff!

Here is an example in full automatic layout mode:


		<AutoGrid:AutoGrid x:Name="LayoutRoot" Columns="2">
			<TextBlock Text="Name"
					   Margin="2"/>
			<TextBox Components:SelectOnFocus.SelectAll="True" Text="{Binding Name, Mode=TwoWay}"
					 Margin="2"
					 Width="150"
					 />
			<TextBlock Text="Type"
					   Margin="2"
					   />
			<ComboBox
					ItemsSource="{Binding Type, Converter={StaticResource EnumSource}}"
					SelectedItem="{Binding Type, Converter={StaticResource EnumValue}}"
					Margin="2"
					Width="150"
					/>
			<TextBlock Text="Width" Margin="2" />
			<TextBox Text="{Binding Width, Mode=TwoWay}"
				 Components:SelectOnFocus.SelectAll="True"
					 Margin="2"
				 Width="150"/>
			<TextBlock Text="Choice List " VerticalAlignment="Top" Margin="2"/>
			<TextBox Width="150"
					 Height="100"
					 Margin="2"
					 AcceptsReturn="True"
					 Text="{Binding ChoiceList, Converter={StaticResource ListToString}, Mode=TwoWay}"/>
		</AutoGrid:AutoGrid>

Which produces this output:

 

You can download the project from here.

, , , ,

5 Comments