WPF 统一网格布局

标签 wpf layout grid uniformgrid

我有一个 ItemsControl,我计划在其中托管一个水果对象列表。我有一个 Fruit 对象列表,它们都有自己的 DataTemplate。我有一个 Grape 对象、一个 Orange 对象和一个 Kiwi 对象。

我想使用 UniformGrid 以便所有单元格具有相同的大小,但我希望 Kiwi 对象仅跨越 1 个单元格,我想要 Grape 跨越 2 个单元格(ColumnSpan = 2),我希望 Orange 控件跨越 4 个单元格(ColumnSpan = 2RowSpan = 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/

相关文章:

wpf - 具有直接ViewModel切换的WPF/MVVM导航

html - 如何在不使用 CSS word-break 属性的情况下停止文本跑出屏幕并破坏布局?

html - 两列 Bootstrap 布局

android - relativelayout 和 View 与layout_toLeftOf 属性在DialogFragment 中不起作用

java - 在Java中绘制段落时更改字体

EXTJS 5 : Why does Ext. grid.Panel 在我将主题从海王星更改为清晰后没有 stripRows 效果

javascript - 使用 js-grid 显示静态数据

c# - 设置 IntervalBarSeries 的标签 (oxyplot)

wpf - 使用WPF中的TaskBarItemInfo作为Win 7任务栏中的进度条

c# - 如何将 MenuItem 从一个 ContextMenu 复制到另一个 ContextMenu