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

pjm*_*ina 5 c# wpf binding interface relativesource

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

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

Property="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ty:ConcreteClassView}}, Path=DataContext.Name}"
Run Code Online (Sandbox Code Playgroud)

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

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}"
Run Code Online (Sandbox Code Playgroud)

给予:

class ConcreteClassView : BaseClassView, INamedElementView { }
Run Code Online (Sandbox Code Playgroud)

好吧,我们假设FindAncestor,AncestorType需要具体类型才能工作.

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

Thxs.

Lie*_*ero 7

FindAncestor,AncestorType可以处理基类,所以你的假设是错误的.

这是证明:这是有效的

<HeaderedContentControl Tag="ABC">
    <TextBlock Text="{Binding Tag, RelativeSource={RelativeSource AncestorType=ContentControl}}" />
</HeaderedContentControl>
Run Code Online (Sandbox Code Playgroud)

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

<Button Tag="ABC">
    <TextBlock Text="{Binding Tag, RelativeSource={RelativeSource AncestorType=ICommandSource}}" />
</Button>
Run Code Online (Sandbox Code Playgroud)

(在.NET 4.5中测试)

那么为什么你的代码不起作用呢?

  1. 可能还有另一个派生自ty的元素:绑定目标和您要查找的元素之间的可视树中的BaseClassView.

这不起作用:

<HeaderedContentControl Tag="ABC">
    <Label>
        <TextBlock Text="{Binding Tag, RelativeSource={RelativeSource AncestorType=ContentControl}}" />
    </Label>
</HeaderedContentControl>
Run Code Online (Sandbox Code Playgroud)

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

  1. 可视树可能已断开连接.例如,弹出控件是逻辑树的一部分,但它有自己的可视树,因此您不能在弹出窗口内使用RelativeSource FindAncestor来查找弹出窗口之外的父级.请注意,当您设置Visibility ="Collapsed"时,也会从可视树中删除这些元素

怎么调试?

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

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

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

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