2011-04-08 34 views
0

这可能是一个骗局,但我找不到任何东西在一个小时左右的搜索和阅读MSDN。嵌套Itemscontrols数据绑定到同一网格

我正在制作基于2D瓦片的游戏,并将ItemsControl绑定到Tiles列表(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<Location>,其中有一个单元,我想要放在该网格上。

<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只是从位置获取列索引。

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

我该怎么办?

+0

您指的是哪个网格作为外部网格?统一网格? – 2011-04-08 13:46:59

+0

我在问题中已澄清。我希望将位置集合放置在5x5 tileGrid中,但我无法弄清楚如何去做。 – David 2011-04-08 13:49:57

回答

1

看起来好像我重复了以前的建议,但是您应该将TileGrid作为ItemsPanel用于位置ItemsControl,并使此ItemsControl成为Tiles ItemsControl的子项。我不明白为什么这是不可能的?

也许你需要在DataTemplate中使用tileGrid做些事情。所以,我认为可以为ItemsControl做同样的事情。

我也可以认为tileGrid中还有其他ColumnDefinitions或RowDefinitions。这样,您就可以使用里面位置的其他电网和使用IsSharedSizeScopeSharedSizeGroup

+0

我遇到的问题是,tileGrid还包含需要定位的其他元素。尝试给我以下错误:“无法显式修改用作ItemsControl的ItemsPanel的Panel的Children集合。ItemsControl为Panel生成子元素。” – David 2011-04-08 13:58:51

+0

发生此异常是因为用作ItemsPanel的面板不能显式包含元素。 Rachel很好地指出了使用ItemContainerStyle替代ItemTemplate的位置属性。我认为你可以在位置的DataTemplate中使用tilePanel,并使用另一个Grid作为Tiles的ItemsPanel。您还需要使用共享大小范围来组合ItemControl(s)中的面板。 – 2011-04-08 19:03:03

0

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