2012-06-12 183 views
1

我有一个ItemsControl我打算主持一个水果对象列表。我有一个Fruit对象的列表,全部都有自己的DataTemplate s。我有一个Grape对象,一个Orange对象和一个Kiwi对象。WPF UniformGrid布局

我想使用一个UniformGrid,以便所有单元具有相同大小,但我想的Kiwi对象仅跨越1细胞,我希望Grape跨越2个细胞(ColumnSpan = 2),我想的Orange控制跨越4细胞(ColumnSpan = 2RowSpan = 2

我该如何做到这一点?

回答

0

你不能这样做行或列中均匀网格跨越 - 见下文

WPF: Is it possible to do a row/column span in UniformGrid?

计算器质询,但你可以实现与一个WrapPanel类似的效果,如果您的项目有统一的尺寸。下面有一个例子

<ItemsControl Width="300"> 
    <ItemsControl.ItemsPanel> 
     <ItemsPanelTemplate> 
      <WrapPanel IsItemsHost="True" /> 
     </ItemsPanelTemplate> 
    </ItemsControl.ItemsPanel> 
    <ItemsControl.Items> 
     <Rectangle Fill="Orange" Height="100" Width="100" /> 
     <Rectangle Fill="Red" Height="100" Width="100" /> 
     <Rectangle Fill="Blue" Height="100" Width="100" /> 
     <Rectangle Fill="Green" Height="100" Width="200" /> 
     <Rectangle Fill="Yellow" Height="100" Width="100" /> 
     <Rectangle Fill="Brown" Height="100" Width="100" /> 
     <Rectangle Fill="Black" Height="100" Width="200" /> 
    </ItemsControl.Items> 
</ItemsControl> 
4

项目在一个UniformGrid不能跨越多个细胞。

为什么不使用常规Grid而是将行/列的高度/宽度设置为*,因此它们的大小都是相同的?如果希望单元格是高度与宽度匹配的完美正方形,请确保将网格的Height绑定到Width,反之亦然。

应当注意的是,你需要在ItemContainerStyle每个元素加入该项目的ItemsPanel前应用网格定位性能,而不是项目本身,因为一个ItemsControl的身体包裹ContentPresenter内(见我的博客文章here为更多详情)

<ItemsControl ItemsSource="{Binding MyCollection}"> 
    <!-- ItemsPanelTemplate --> 
    <ItemsControl.ItemsPanel> 
     <ItemsPanelTemplate> 
      <Grid> 
       <Grid.RowDefinitions> 
        <RowDefinition Height="*" /> 
        <RowDefinition Height="*" /> 
        <RowDefinition Height="*" /> 
       </Grid.RowDefinitions> 
       <Grid.ColumnDefinitions> 
        <ColumnDefinition Width="*" /> 
        <ColumnDefinition Width="*" /> 
        <ColumnDefinition Width="*" /> 
       </Grid.ColumnDefinitions> 
      </Grid> 
     </ItemsPanelTemplate> 
    </ItemsControl.ItemsPanel> 

    <!-- ItemContainerStyle --> 
    <ItemsControl.ItemContainerStyle> 
     <Style> 
      <Setter Property="Grid.Column" 
        Value="{Binding ColumnIndex}" /> 
      <Setter Property="Grid.Row" 
        Value="{Binding RowIndex}" /> 

      <!-- Can either use a DataTrigger to determine these values, 
       or store them on the object itself --> 
      <Setter Property="Grid.RowSpan" 
        Value="{Binding RowSpan}" /> 
      <Setter Property="Grid.ColumnSpan" 
        Value="{Binding ColumnSpan}" /> 
     </Style> 
    </ItemsControl.ItemContainerStyle> 
</ItemsControl>