Can I get headers in a WPF grid getting its rows from a data template?

c#, wpf, xaml

Solution

You can use Grid.IsSharedSizeScope attached property

<StackPanel Orientation="Vertical" Grid.IsSharedSizeScope="True">
  <Grid Margin="0, 10, 0, 0">
    <Grid.ColumnDefinitions>
      <ColumnDefinition SharedSizeGroup="First" Width="40" />
      <ColumnDefinition SharedSizeGroup="Second" Width="70" />
    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
      <RowDefinition />
    </Grid.RowDefinitions>
    <TextBlock Grid.Column="0" Grid.Row="0"
            Text="header 1" />
    <TextBlock Grid.Column="1" Grid.Row="0"
            Text="header 2" />
  </Grid>
  <ItemsControl ItemsSource="{Binding Entities}">
    <ItemsControl.ItemTemplate>
      <DataTemplate>
        <StackPanel Orientation="Vertical">
          <Grid Margin="0, 10, 0, 0">
            <Grid.ColumnDefinitions>
              <ColumnDefinition SharedSizeGroup="First" />
              <ColumnDefinition SharedSizeGroup="Second" />
            </Grid.ColumnDefinitions>
            <Grid.RowDefinitions>
              <RowDefinition />
            </Grid.RowDefinitions>
            <TextBlock Grid.Column="0" Grid.Row="0"
               Text="{Binding Property1}" />
            <TextBlock Grid.Column="1" Grid.Row="0"
               Text="{Binding Property2}" />
          </Grid>
        </StackPanel>
      </DataTemplate>
    </ItemsControl.ItemTemplate>
  </ItemsControl>
</StackPanel>

Problem

I am implementing a headered table using grids above each other, so I can specify columns headers. There is one grid for headers, and one grid for every row in the table. It is not very practical, header widths has to be specified twice. Maybe I instead can have a ListView/DataGrid without all styling? How can I get rid of this multi Grid approach? Here is what I got: ``` <StackPanel Orientation="Vertical"> <Grid Margin="0, 10, 0, 0"> <Grid.ColumnDefinitions> <ColumnDefinition Width="40" /> <ColumnDefinition Width="70" /> </Grid.ColumnDefinitions> <Grid.RowDefinitions> <RowDefinition /> </Grid.RowDefinitions> <TextBlock Grid.Column="0" Grid.Row="0" Text="header 1" /> <TextBlock Grid.Column="1" Grid.Row="0" Text="header 2" /> </Grid> <ItemsControl ItemsSource="{Binding Entities}"> <ItemsControl.ItemTemplate> <DataTemplate> <StackPanel Orientation="Vertical"> <Grid Margin="0, 10, 0, 0"> <Grid.ColumnDefinitions> <ColumnDefinition Width="40" /> <ColumnDefinition Width="70" /> </Grid.ColumnDefinitions> <Grid.RowDefinitions> <RowDefinition /> </Grid.RowDefinitions> <TextBlock Grid.Column="0" Grid.Row="0" Text="{Binding Property1}" /> <TextBlock Grid.Column="1" Grid.Row="0" Text="{Binding Property2}" /> </Grid> </StackPanel> </DataTemplate> </ItemsControl.ItemTemplate> </ItemsControl> </StackPanel> ```

Original source