gpt4 book ai didi

c# - 是否可以使用指向基类型的 AncestorType 进行 WPF RelativeSource 绑定(bind)?

转载 作者:太空狗 更新时间:2023-10-29 23:00:57 25 4
gpt4 key购买 nike

我想将属性绑定(bind)到在其 DataContext 中具有 ViewModel 的父容器 View 。

当父级是 ConcreteClassView 的直接实例时,这段代码工作得很好:

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

但是,当尝试通过基类或接口(interface)定位时,找不到父级。示例:

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 需要具体类型才能工作。

但是是否有任何变通方法可以仅基于基类或实现给定接口(interface)来定位祖先?

谢谢。

最佳答案

FindAncestor、AncestorType 与基类一起工作,因此您的假设是错误的。

这是证明:这是可行的

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

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

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

(在 .NET 4.5 中测试)

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

  1. 在绑定(bind)目标和您要查找的元素之间的可视化树中,可能还有另一个派生自 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"
  2. 时,元素也会从可视树中删除

如何调试?

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

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

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

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

关于c# - 是否可以使用指向基类型的 AncestorType 进行 WPF RelativeSource 绑定(bind)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13194231/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com