是否可以使用AncestorType指向基类型的WPF RelativeSource绑定?

时间:2012-11-02 11:22:34

标签: c# wpf binding interface relativesource

我想将属性绑定到其DataContext中具有ViewModel的父容器视图。

当父级是 ConcreteClassView 的直接实例时,此代码非常有效:

Property="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ty:ConcreteClassView}}, Path=DataContext.Name}"

但是,在尝试通过基类或接口找到父级时,找不到父级。 样品:

PropertyB="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ty:BaseClassView}}, Path=DataContext.Name}"

PropertyB="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ty:INamedElementView}}, Path=DataContext.Name}"

给予:

class ConcreteClassView : BaseClassView, INamedElementView { }

好的,我们假设 FindAncestor AncestorType 需要具体的工作类型。

但是,有什么解决方法可以根据基类或实现给定的接口来定位祖先吗?

Thxs。

1 个答案:

答案 0 :(得分:7)

FindAncestor,AncestorType可以使用基类,所以你的假设是错误的。

以下是证明:此作品

<HeaderedContentControl Tag="ABC">
    <TextBlock Text="{Binding Tag, RelativeSource={RelativeSource AncestorType=ContentControl}}" />
</HeaderedContentControl>

它也适用于接口(Button实现ICommandSource):

<Button Tag="ABC">
    <TextBlock Text="{Binding Tag, RelativeSource={RelativeSource AncestorType=ICommandSource}}" />
</Button>

(在.NET 4.5中测试)

为什么您的代码不起作用?

  1. 可能还有一个派生自ty的元素:绑定目标和您要查找的元素之间的可视树中的BaseClassView。
  2. 这不起作用:

    <HeaderedContentControl Tag="ABC">
        <Label>
            <TextBlock Text="{Binding Tag, RelativeSource={RelativeSource AncestorType=ContentControl}}" />
        </Label>
    </HeaderedContentControl>
    

    Label也是从ContentControl继承的,因此Binding Source在这种情况下是Label

    1. 可能会断开Visual Tree的连接。例如,Popup控件是Logical Tree的一部分,但它有自己的可视化树,因此您无法在弹出窗口中使用RelativeSource FindAncestor来查找弹出窗口之外的父级。请注意,当您设置Visibility =&#34; Collapsed&#34;
    2. 时,也会从可视树中删除这些元素

      如何调试?

      1. 您可以使用转换器调试绑定。只需指定RelativeSource和一些假转换器并将路径留空。然后,您可以将断点放置到转换器,其中value是您的绑定源。

      2. 使用绑定的元素的加载事件将所有可视父项写入调试窗口

      3. 编辑:现在,在Visual Studio 2015中,您可以使用实时可视树资源管理器在运行时检查可视化树(类似于浏览器&#39;开发人员工具)可以检查dom元素)。使用此工具,您应该能够在几秒钟内找到应用程序中的错误。

        https://msdn.microsoft.com/en-us/library/mt270227.aspx