如何使用对象中指定的行/列将“ObservableCollection"绑定到网格? [英] How to bind an `ObservableCollection` to Grid with Rows/Columns specified in the objects?
问题描述
我在网格中有这样的东西:
I have something like this inside a grid:
<Ellipse Grid.Row="{Binding Path=Game.Tiles[2].Row}"
Grid.Column="{Binding Path=Game.Tiles[2].Column}"
Fill="{Binding Game.Tiles[2].FillColor}"
Stroke ="{StaticResource TileStroke}"></Ellipse>
如何在不输入 24 次的情况下枚举所有 24 个对象?
How do I enumerate over all 24 objects without typing this 24 times?
推荐答案
为了显示对象的列表/集合,您需要使用各种ItemsControl".在这种情况下,以下片段可能会有所帮助:
In order to have a list/collection of objects displayed, you need to employ an "ItemsControl" of sorts. In this case, the following fragment might be of help:
<ItemsControl ItemsSource="{Binding Game.Tiles}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="*"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
</Grid>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemContainerStyle>
<Style>
<Setter Property="Grid.Column" Value="{Binding Column}" />
<Setter Property="Grid.Row" Value="{Binding Row}" />
</Style>
</ItemsControl.ItemContainerStyle>
<ItemsControl.ItemTemplate>
<DataTemplate DataType="{x:Type local:Position}">
<Ellipse Fill="{Binding FillColor}"
Stroke="{StaticResource TileStroke}"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
记住为 DataTemplate 放入正确的数据类型,并将足够的行/列放入网格中以保存您的数据.
Remember to put in the right DataType for the DataTemplate and enough rows/columns into the Grid to hold your data.
此外,包含未知数量的行/列也不是那么容易.如果您对此感兴趣,我可以向您提供解决方案,但原始帖子读起来像是游戏板的想法 - 就像跳棋 - 所以我假设列/行的数量是恒定的.
Also it is not quite as easy to include an unknown number of rows/columns. If that is of interest, I could be getting back to you with a solution, but the original post read like the idea of a game board - like checkers - so I assume the number of columns/rows is constant.
这篇关于如何使用对象中指定的行/列将“ObservableCollection"绑定到网格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!