pjm*_*ina 5 c# wpf binding interface relativesource
我想将属性绑定到其DataContext中具有ViewModel的父容器视图.
当父是ConcreteClassView的直接实例时,此代码非常有效:
Property="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ty:ConcreteClassView}}, Path=DataContext.Name}"
Run Code Online (Sandbox Code Playgroud)
但是,在尝试通过基类或接口找到父级时,找不到父级.样品:
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}"
Run Code Online (Sandbox Code Playgroud)
给予:
class ConcreteClassView : BaseClassView, INamedElementView { }
Run Code Online (Sandbox Code Playgroud)
好吧,我们假设FindAncestor,AncestorType需要具体类型才能工作.
但是,有什么解决方法可以根据基类或实现给定的接口来定位祖先?
Thxs.
FindAncestor,AncestorType可以处理基类,所以你的假设是错误的.
这是证明:这是有效的
<HeaderedContentControl Tag="ABC">
<TextBlock Text="{Binding Tag, RelativeSource={RelativeSource AncestorType=ContentControl}}" />
</HeaderedContentControl>
Run Code Online (Sandbox Code Playgroud)
它也适用于接口(Button实现ICommandSource):
<Button Tag="ABC">
<TextBlock Text="{Binding Tag, RelativeSource={RelativeSource AncestorType=ICommandSource}}" />
</Button>
Run Code Online (Sandbox Code Playgroud)
(在.NET 4.5中测试)
那么为什么你的代码不起作用呢?
这不起作用:
<HeaderedContentControl Tag="ABC">
<Label>
<TextBlock Text="{Binding Tag, RelativeSource={RelativeSource AncestorType=ContentControl}}" />
</Label>
</HeaderedContentControl>
Run Code Online (Sandbox Code Playgroud)
Label也是从ContentControl继承的,因此在这种情况下Binding Source是Label
怎么调试?
您可以使用转换器来调试绑定.只需指定RelativeSource和一些假转换器并将路径留空.然后,您可以将断点放置到转换器,其中value是您的绑定源.
使用绑定的元素的加载事件将所有可视父项写入调试窗口
编辑:现在在Visual Studio 2015中,您可以使用Live Visual Tree资源管理器在运行时检查可视化树(类似于浏览器的开发人员工具可以检查dom元素).使用此工具,您应该能够在几秒钟内找到应用程序中的错误.
https://msdn.microsoft.com/en-us/library/mt270227.aspx
| 归档时间: |
|
| 查看次数: |
3018 次 |
| 最近记录: |