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

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

问题描述:

我正在实现一个使用网格上的对齐表,所以我可以指定列标题。有一个网格用于标题,一个网格用于表格中的每一行。这不是很实用,标题宽度必须指定两次。也许我可以有一个没有所有样式的ListView/DataGrid?我可以在WPF网格中获取标题,从数据模板中获取它的行吗?

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

这里是我的了:

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

可以使用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> 
+0

没有工作,我想SharedSizeGroup = “A”,SharedSizeGroup = “B” 等,我只在第一组ColumnDefinitions中指定宽度。 – 2013-03-25 10:24:10

+0

也许这也是一个黑客使用多个网格。 – 2013-03-25 10:27:35

+0

@AndersLindén:我的错误:您必须将Grid.IsSharedSizeScope =“True”作为StackPanel的属性 – mathieu 2013-03-25 10:33:41