6

我想将属性绑定到在其 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 { }

好的,我们假设FindAncestorAncestorType需要具体类型才能工作。

但是有任何解决方法可以仅基于基类或实现给定接口来定位祖先吗?

谢谢。

4

1 回答 1

8

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 派生的元素。

这不起作用:

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

Label 也是继承自 ContentControl,所以本例中 Binding Source 为 Label

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

如何调试?

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

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

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

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

于 2015-04-03T11:55:08.850 回答