WPF绑定到ItemsControl的家长从孩子ItemsControl的数据模板内 [英] WPF Binding to parent ItemsControl from inside of child ItemsControl data template

查看:807
本文介绍了WPF绑定到ItemsControl的家长从孩子ItemsControl的数据模板内的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好了,所以我有一个时髦的人在这里......我需要能够从一个孩子的ItemsControl数据模板内绑定到父母的ItemsControl的属性:

Okay so I have a funky one here...I need to be able to bind to a parent ItemsControl's properties from inside of a child ItemsControl data template:

<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(外集合)是以下类型的:

Let's assume that MyParentCollection (the outer collection) is of the following type:

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

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

And let's assume that MyChildObject from the above class is of the following type:

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

我怎么可以绑定到MyParentCollection.Value从内部数据模板里面?我真的不能使用FindAncestor按类型,因为它们都各层次使用相同的类型。我想也许我可以把名字写在外部收集和使用的ElementName标记在内部具有约束力,但还是没能解决该房产。

How can I bind to MyParentCollection.Value from inside of the inner data template? I can't really use a FindAncestor by type because they both all levels use the same types. I thought maybe I could put a name on the outer collection and use an ElementName tag in the inner binding, but that still couldn't resolve the property.

有什么想法?我卡在这一个...

Any thoughts? I'm stuck on this one...

推荐答案

节省孩子的ItemsControl可以工作在标签的父项

saving the parent item in the tag of the child itemscontrol could work

    <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>

它不是测试,但给你一个提示在正确的方向:)

its not tested but give you a hint in the right direction :)

这篇关于WPF绑定到ItemsControl的家长从孩子ItemsControl的数据模板内的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆