views:

69

answers:

1

I am using a grid by the definition of appropriateness defined in this question Grid vs Stackpanel. However when working with grids you have to define the controls position inside them explicitly in the grid. This becomes a pain when having to reorder controls or when adding a new control to the grid. With the code provided as an example, is there a way to get the rows and columns for the text and text boxes to line up while being easy to modify or expand later?

<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="3*"/>
        <ColumnDefinition Width="7*"/>
    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
        <RowDefinition />
        <RowDefinition />
        <RowDefinition />
    </Grid.RowDefinitions>
    <TextBlock Text="Value One:"   Grid.Row="0" Grid.Column="0"/>
        <TextBox x:Name="TextBoxOne"   Grid.Row="0" Grid.Column="1"/>

    <TextBlock Text="Value Two:"   Grid.Row="1" Grid.Column="0"/>
        <TextBox x:Name="TextBoxTwo"   Grid.Row="1" Grid.Column="1"/>

    <TextBlock Text="Value Three:" Grid.Row="2" Grid.Column="0"/>
        <TextBox x:Name="TextBoxThree" Grid.Row="2" Grid.Column="1"/>
</Grid>
+2  A: 

I wrote a custom control I use that makes it extremely easy to do this, but before I created it I generally used this sort of thing:

<ControlTemplate x:Key="ColumnsTemplate" TargetType="HeaderedContentControl">
  <Grid>
    <Grid.ColumnDefinitions>
      <ColumnDefinition Width="3*" />
      <ColumnDefinition Width="7*" />
    </Grid.ColumnDefinitions>
    <ContentPresenter Grid.Column="0" ContentSource="Header" />
    <ContentPresenter Grid.Column="1" />
  </Grid>
</ControlTemplate>

<ItemsControl ... ItemTemplate="{StaticResource ColumnsTemplate}">
  <HeaderedContentControl Header="Value One:">
    <TextBox x:Name="TextBoxOne" />
  </HeaderedContentControl>
  <HeaderedContentControl Header="Value Two:">
    <TextBox x:Name="TextBoxTwo" />
  </HeaderedContentControl>
  ...
</ItemsControl>

This allows easy add/remove of items from the ItemsControl, or better yet, data binding.

If you prefer auto-sizing on the grid rather than star sizing (3* and 7*) you can use a shared sizing scope by setting IsSharedSizeScope on the ItemsControl and SharedSizeGroup on the first ColumnDefinition.

Another option is GridView, but I find it more difficult to use for this purpose.

Ray Burns
That is the exact pattern I was looking for and you showed me ControlTemplate as well, Thanks.
JustSmith