我可以在WPF网格中获取标题从数据模板中获取行吗?

时间:2013-03-25 09:21:31

标签: c# wpf xaml

我正在使用彼此之上的网格实现一个带标题的表,因此我可以指定列标题。标题有一个网格,表格中的每一行都有一个网格。它不是很实用,标题宽度必须指定两次。也许我可以在没有所有样式的情况下拥有ListView / DataGrid?

如何摆脱这种多网格方法?

这是我得到的:

<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>

1 个答案:

答案 0 :(得分:10)

您可以使用Grid.IsSharedSizeScope附加属性

<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>