能否使用AncestorType指向基类型来创建WPF相对源绑定?

7
我想将一个属性绑定到父容器视图,该视图具有其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需要具体类型才能工作。
但是是否有任何解决方法可以基于基类或实现给定接口来定位祖先元素呢?
谢谢。

1
奇怪的是,AncestorType 必须与基类一起使用。 - Vlad
你检查过命名空间是否正确了吗?也许 INamedElementView 在其他的命名空间里? - Vlad
谢谢 @Vlad,它们都在同一个命名空间中定义。而 ty 别名引用了它。 - pjmolina
我有同样的问题。 - Bitfiddler
@pjmolina:你解决了这个问题吗?它是我在答案中描述的情况之一吗? - Liero
抱歉 @Liero,这个问题已经是4年前的事了。我现在没有上下文来重现它。 - pjmolina
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>

标签也是从ContentControl继承而来,所以在这种情况下,Binding Source是Label

  1. 可视树可能会被断开。例如Popup控件是逻辑树的一部分,但它有自己的可视树,因此您不能在popup内使用RelativeSource FindAncestor查找popup外的父级。请注意,当您设置Visibility =“Collapsed”时,元素也会从可视树中删除。

如何调试?

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

  2. 使用具有绑定的元素的loaded事件,将所有可视父级写入Debug窗口

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

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接