嵌套项控件将数据绑定到同一个网格

本文关键字:同一个 网格 数据绑定 控件 嵌套 | 更新日期: 2023-09-27 17:49:21

这可能是骗人的,但我在MSDN上搜索了一个小时左右,什么也没找到。

我正在制作一款基于贴图的2D游戏,并将ItemsControl绑定到贴图列表(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>

每个Tile都有一个5x5的内部网格,因为我需要能够在每个Tile的不同位置放置单位。每个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只是从Location获取列索引。

问题是,我不能从ItemsControl内部绑定到tileGrid的列和行。有些人建议将Grid放在Locations ItemsControl中,但这不起作用,因为它需要成为外部Tiles ItemsControl的子控件。

我能做什么?

嵌套项控件将数据绑定到同一个网格

这似乎是我重复以前的建议,但你应该使用tileGrid作为ItemsPanel的位置ItemsControl,并使这个ItemsControl是tile ItemsControl的孩子。我不明白为什么这是不可能的?

也许你需要在DataTemplate中对tileGrid做一些事情。我认为对ItemsControl做同样的事情是可能的。

我还可以假设在tileGrid中有额外的columndefinition或rowdefinition。通过这种方式,你可以在Locations内部使用另一个Grid,并使用IsSharedSizeScope和SharedSizeGroup

将其定义与tileGrid绑定。

设置网格。列和网格。ItemsControl中的行。ItemContainerStyle,而不是DataTemplate。每个项目都包装在一个ContentPresenter中,所以Grid。列和网格。行不能正确应用