我有一个 ItemsControl
,我计划在其中托管一个水果对象列表。我有一个 Fruit
对象列表,它们都有自己的 DataTemplate
。我有一个 Grape
对象、一个 Orange
对象和一个 Kiwi
对象。
我想使用 UniformGrid
以便所有单元格具有相同的大小,但我希望 Kiwi
对象仅跨越 1 个单元格,我想要 Grape
跨越 2 个单元格(ColumnSpan = 2
),我希望 Orange
控件跨越 4 个单元格(ColumnSpan = 2
和 RowSpan = 2
)
我怎样才能做到这一点?
最佳答案
UniformGrid
中的项目不能跨越多个单元格。
为什么不使用常规的Grid
,而是将行/列的高度/宽度设置为*
,这样它们的大小都一样?如果您希望单元格成为高度与宽度匹配的完美正方形,请务必将网格的 Height
绑定(bind)到 Width
,反之亦然。
应该注意的是,您需要在 ItemContainerStyle
中应用 Grid 定位属性,而不是在项目本身上,因为 ItemsControl
将每个元素包装在 >ContentPresenter
,然后将该项目添加到 ItemsPanel
(有关详细信息,请参阅我的博客文章 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>
关于WPF 统一网格布局,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10999715/