【问题标题】:Is possible to make a WPF RelativeSource binding with AncestorType pointing to a base type?是否可以使用指向基类型的 AncestorType 进行 WPF RelativeSource 绑定?
【发布时间】:2012-11-02 11:22:33
【问题描述】:

我想将一个属性绑定到在其 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 需要具体类型才能工作。

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

谢谢。

【问题讨论】:

  • 奇怪,AncestorType 也必须与基类一起使用。
  • 你检查过命名空间是否正确吗?也许INamedElementView 在其他命名空间中?
  • 感谢@Vlad 所有这些都定义在同一个命名空间中。 ty 别名引用它。
  • 我也有同样的问题。
  • @pjmolina:你解决了这个问题吗?这是我在回答中描述的案例之一吗?

标签: c# wpf binding interface relativesource


【解决方案1】:

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

如何调试?

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

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-06-04
    • 1970-01-01
    • 1970-01-01
    • 2018-09-01
    • 1970-01-01
    • 2021-04-24
    • 1970-01-01
    相关资源
    最近更新 更多