This may be a dupe, but I couldn't f开发者_如何学JAVAind anything in an hour or so of searching and reading MSDN.
I'm making a 2D tile-based game and have an ItemsControl bound to a list of Tiles (C# class). This works great.
<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>
There's an inner 5x5 Grid for each Tile since I need to be able to place units at various locations on each Tile. Each Tile
contains a List<Location>
where there is a unit, which I want to place on that Grid.
<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>
Where ColumnConverter and RowConverter just get the column index from a Location.
The problem is that I can't bind to tileGrid's Column and Row from inside the ItemsControl. Some people have suggested putting the Grid inside the Locations ItemsControl, but that doesn't work because it needs to be a child of the outer Tiles ItemsControl.
What can I do?
It seems like I repeat previous suggestions, but you should use tileGrid as ItemsPanel for Locations ItemsControl and make this ItemsControl to be a child of Tiles ItemsControl. I don't understand why it is impossible?
Perhaps you need to do something with tileGrid within DataTemplate. So, I think is is possible to do the same for ItemsControl.
I also can assume that there are additional ColumnDefinitions or RowDefinitions in tileGrid. In this way you can use another Grid inside Locations and bind its definitions with tileGrid using IsSharedSizeScope and SharedSizeGroup
Set the Grid.Column and Grid.Row in the ItemsControl.ItemContainerStyle, not in the DataTemplate. Each item is wrapped in a ContentPresenter so the Grid.Column and Grid.Row are not getting applied properly
精彩评论