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

时间:2013-06-19 08:55:40

标签: c# .net wpf binding

好的,我在这里有一个时髦的...我需要能够从子ItemsControl数据模板内部绑定到父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.Value?我不能真正按类型使用FindAncestor,因为它们都使用相同的类型。我想也许我可以在外部集合上添加一个名称,并在内部绑定中使用ElementName标记,但仍然无法解析该属性。

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

2 个答案:

答案 0 :(得分:17)

将子项保存在子项目控件的标记中可以正常工作

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

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

答案 1 :(得分:0)

如其他答案所示,不需要绑定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>
相关问题