我希望将属性绑定到在其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需要具体的类型才能工作。
但是有什么解决办法可以仅仅基于基类或实现给定的接口来定位祖先呢?
特克斯。
发布于 2015-04-03 11:55:08
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测试)
,那么为什么您的代码不能工作?
这不管用:
<HeaderedContentControl Tag="ABC">
<Label>
<TextBlock Text="{Binding Tag, RelativeSource={RelativeSource AncestorType=ContentControl}}" />
</Label>
</HeaderedContentControl>
标签也是从ContentControl继承的,所以在本例中绑定源是标签
如何调试?
编辑:现在在Visual 2015中,您可以使用Live explorer在运行时检查可视化树(类似于浏览器开发人员的工具可以检查元素)。使用此工具,您应该能够在几秒钟内在应用程序中找到bug。
https://stackoverflow.com/questions/13194231
复制相似问题