【问题标题】:Nested Itemscontrols data binding to the same GridNested Itemscontrols 将数据绑定到同一个 Grid
【发布时间】:2011-04-08 13:27:27
【问题描述】:

这可能是个骗子,但我在搜索和阅读 MSDN 的一个小时左右内找不到任何东西。

我正在制作一个基于图块的 2D 游戏,并将 ItemsControl 绑定到一个图块列表(C# 类)。这很好用。

<ItemsControl ItemsSource="{Binding Tiles}">
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <UniformGrid Rows="{Binding Board.Rows}" Columns="{Binding Board.Columns}"/>
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
    <ItemsControl.Resources>
        <DataTemplate DataType="{x:Type local:Tile}">
            <Grid x:Name="tileGrid" Background="{Binding TileImage}"/>
        </DataTemplate>
    </ItemsControl.Resources>
<ItemsControl>

每个图块都有一个内部 5x5 网格,因为我需要能够在每个图块的不同位置放置单元。每个Tile 都包含一个List&lt;Location&gt;,其中有一个单元,我想将其放置在该网格上。

<Grid x:Name="tileGrid" Background="{Binding TileImage}">
    <ColumnDefinition snipped - there's 5 columns and 5 rows>
    <ItemsControl ItemsSource="{Binding Locations}">
        <ItemsControl.Resources>
            <DataTemplate DataType="{x:Type sys:Int32}">
                <Image Source="unit.bmp"
                        Grid.Column="{Binding Converter={StaticResource ColumnConverter}}"
                        Grid.Row="{Binding Converter={StaticResource RowConverter}}"/>
            </DataTemplate>
        </ItemsControl.Resources>
    </ItemsControl>

ColumnConverter 和 RowConverter 只是从 Location 中获取列索引。

问题是我无法从 ItemsControl 内部绑定到 tileGrid 的 Column 和 Row。有人建议将 Grid 放在 Locations ItemsControl 中,但这不起作用,因为它需要是外部 Tiles ItemsControl 的子级。

我能做什么?

【问题讨论】:

  • 你指的是哪个网格作为外网格?统一网格?
  • 我已经在问题中澄清了。我希望将位置集合定位在 5x5 tileGrid 内,但我不知道该怎么做。

标签: c# wpf


【解决方案1】:

似乎我重复了之前的建议,但您应该使用 tileGrid 作为 Locations ItemsControl 的 ItemsPanel,并使此 ItemsControl 成为 Tiles ItemsControl 的子项。我不明白为什么这是不可能的?

也许您需要对 DataTemplate 中的 tileGrid 做一些事情。所以,我认为可以对 ItemsControl 做同样的事情。

我也可以假设在 tileGrid 中有额外的 ColumnDefinitions 或 RowDefinitions。通过这种方式,您可以在 Locations 中使用另一个 Grid,并使用 IsSharedSizeScopeSharedSizeGroup 将其定义与 tileGrid 绑定

【讨论】:

  • 我遇到的问题是 tileGrid 还包含其他需要定位的元素。尝试这样做会给我以下错误:“无法显式修改用作 ItemsControl 的 ItemsPanel 的 Panel 的 Children 集合。ItemsControl 为 Panel 生成子元素。”
  • 发生此异常是因为用作 ItemsPanel 的 Panel 不能显式包含元素。 Rachel 很好地指出了使用 ItemContainerStyle 而不是 ItemTemplate 作为位置属性。我认为您可以在位置的 DataTemplate 中保留 tilePanel,并使用另一个 Grid 作为 Tiles 的 ItemsPanel。您还需要使用共享大小范围来组合 ItemControl(s) 中的面板。
【解决方案2】:

在 ItemsControl.ItemContainerStyle 中设置 Grid.Column 和 Grid.Row,而不是在 DataTemplate 中。每个项目都包装在 ContentPresenter 中,因此 Grid.Column 和 Grid.Row 没有得到正确应用

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-03-15
    • 1970-01-01
    • 1970-01-01
    • 2014-12-11
    • 2012-07-25
    • 2016-06-24
    • 1970-01-01
    相关资源
    最近更新 更多