【问题标题】:Arranging collection items in a grid在网格中排列集合项目
【发布时间】:2011-04-17 10:59:37
【问题描述】:

我想将集合中的项目排列在具有特定列数和行数(例如 4x6)的网格中。每个项目都公开了依赖属性(整数)X 和 Y,并且应该放置在网格的相关单元格中。请注意,集合在运行时可能会发生变化,这应该会更新网格项目。

我找不到任何好的解决方案。但也许不使用代码隐藏甚至是可能的?

不介意转换之类的。这东西无论如何都会改变。使用的集合类并不重要。 (你可以选择一个。)

我该如何解决这个问题? 我们欢迎任何适当的建议,谢谢。

【问题讨论】:

    标签: wpf collections grid dependency-properties


    【解决方案1】:
    <ItemsControl ItemsSource="{Binding YourItems}">
        <ItemsControl.ItemsPanel>
            <ItemsPanelTemplate>
                <Grid/>
            </ItemsPanelTemplate>
        </ItemsControl.ItemsPanel>
        <ItemsControl.ItemContainerStyle>
            <Style>
                <Setter Property="Grid.Column" Value="{Binding X}"/>
                <Setter Property="Grid.Row" Value="{Binding Y}"/>
            </Style>
        </ItemsControl.ItemContainerStyle>
    </ItemsControl>
    

    【讨论】:

    • 很好的解决方案,虽然你需要把 Grid.RowDefinitions 和 Grid.ColumnDefinitions 放在那里,X 和 Y 的最大值分别作为 RowDefinition 和 ColumnDefinition....否则它们只会相互重叠.
    • 值得一提的是,您必须使用ItemContainerStyle 来执行此操作。您不能只在ItemTemplate 中设置Grid.RowGrid.Column,因为ItemTemplate 生成的任何元素都包装在ItemsControl 生成的容器中,而Grid.RowGrid.Column 有设置在该容器上,以便Grid 看到它们。
    • 工作正常,谢谢。 @罗伯特:感谢您的解释。我什至不知道,网格生成容器...
    猜你喜欢
    • 1970-01-01
    • 2013-06-27
    • 1970-01-01
    • 2013-05-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多