从子ItemsControl数据模板内部绑定到父ItemsControl



我需要能够从子ItemsContro数据模板内部绑定到父ItemsControl的属性:

<ItemsControl ItemsSource="{Binding Path=MyParentCollection, UpdateSourceTrigger=PropertyChanged}">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
                <ItemsControl ItemsSource="{Binding Path=MySubCollection}">
                    <ItemsControl.ItemTemplate>
                        <DataTemplate>
                            <TextBlock Text="{Binding Path=MyParentCollection.Value, UpdateSourceTrigger=PropertyChanged}"/>
                        </DataTemplate>
                    </ItemsControl.ItemTemplate>
                </ItemsControl>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

让我们假设MyParentCollection(外部集合)是以下类型:

public class MyObject
{
    public String Value { get; set; }
    public List<MyChildObject> MySubCollection { get; set;
}

我们假设上面类中的MyChildObject是以下类型:

public class MyChildObject
{
    public String Name { get; set; }
}

如何绑定到MyParentCollection。值从内部数据模板?我不能按类型使用FindAncestor因为它们所有级别都使用相同的类型。我想也许我可以在外部集合上放一个名字,并在内部绑定中使用一个ElementName标签,但这仍然无法解析属性。

任何想法吗?

将父项保存在子项控件的标签中可以工作

    <DataTemplate>
            <ItemsControl ItemsSource="{Binding Path=MySubCollection}" Tag="{Binding .}">
                <ItemsControl.ItemTemplate>
                    <DataTemplate>
                        <TextBlock Text="{Binding Path=Tag.Value, RelativeSource={RelativeSource  AncestorType={x:Type ItemsControl}}}"/>
                    </DataTemplate>
                </ItemsControl.ItemTemplate>
            </ItemsControl>
    </DataTemplate>

没有经过测试,但是给你一个正确方向的提示:)

根据另一个答案的建议,不需要绑定Tag。所有的数据都可以从ItemControl的DataContext中获得(并且这个标记Tag="{Binding}"只是将DataContext复制到Tag属性中,这是多余的)。

<ItemsControl ItemsSource="{Binding Path=MyParentCollection}">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <ItemsControl ItemsSource="{Binding Path=MySubCollection}">
                <ItemsControl.ItemTemplate>
                    <DataTemplate>
                        <TextBlock Text="{Binding Path=DataContext.Value, RelativeSource={RelativeSource AncestorType=ItemsControl}}"/>
                    </DataTemplate>
                </ItemsControl.ItemTemplate>
            </ItemsControl>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

最新更新