2011-04-08 35 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沒有得到正確應用