我希望将属性绑定到在其ViewModel中具有DataContext的父容器视图。
当父代码是 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 { }
好的,假设 FindAncestor , AncestorType 需要具体的类型才能工作。
但是有什么解决办法可以仅仅基于基类或实现给定的接口来定位祖先呢?
特克斯。
FindAncestor,AncestorType确实使用了基类 ,所以您的假设是错误的。
这里有证据:这是可行的。
<HeaderedContentControl Tag="ABC">
<TextBlock Text="{Binding Tag, RelativeSource={RelativeSource AncestorType=ContentControl}}" />
</HeaderedContentControl>
它也适用于接口(Button实现ICommandSource):
<Button Tag="ABC">