Skip to main content
 首页 » 编程设计

c#之如何使用对象中指定的行/列将 `ObservableCollection` 绑定(bind)到网格

2024年02月13日1398°冷暖

我在网格中有这样的东西:

    <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 个对象?

请您参考如下方法:

为了显示对象的列表/集合,您需要使用某种“ItemsControl”。在这种情况下,以下片段可能会有所帮助:

<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 放入正确的 DataType,并将足够的行/列放入 Grid 中以保存您的数据。

此外,包含未知数量的行/列也不是那么容易。如果您对此感兴趣,我可能会通过解决方案回复您,但原始帖子读起来像是游戏板的概念 - 就像跳棋 - 所以我假设列数/行数是恒定的。