【问题标题】:WPF Binding to parent ItemsControl from inside of child ItemsControl data templateWPF 从子 ItemsControl 数据模板内部绑定到父 ItemsControl
【发布时间】:2013-06-15 17:40:31
【问题描述】:

我需要能够从子 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 标记,但这仍然无法解析该属性。

有什么想法吗?

【问题讨论】:

  • 不能使用 FindAncestor 模式,同时指定 Type 和 Ancestor 级别吗?
  • hmmm,没想到祖先级别……我去看看
  • 我似乎无法让它工作,哦,好吧

标签: c# .net wpf binding


【解决方案1】:

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

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

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

【讨论】:

  • 当天的黑客攻击,但仍然挽救了这一天。非常感谢!我希望标记绑定只是对绑定上下文进行引用,而不是复制上下文中的内容。
  • 今天很棒的 hack!
【解决方案2】:

不需要绑定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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多