WPF 数据绑定的“RelativeSource FindAncestor"究竟是做什么的?做? [英] What exactly does WPF Data Binding's "RelativeSource FindAncestor" do?
问题描述
我目前正在使用 WPF 用户控件(我的 XAML 文件的根元素是UserControl"),我知道它托管在一个 Window 中.如何使用数据绑定访问 Window 的属性?
I am currently working within a WPF user control (the root element of my XAML file is "UserControl"), which I know is being hosted inside a Window. How can I access a property of the Window using data binding?
有谁知道为什么很简单
<Binding RelativeSource="{RelativeSource FindAncestor, AncestorType={x:Type Window}}" Path="..." />
不起作用?我得到的错误信息是:
does not work? The error message I get is:
System.Windows.Data 警告:4:无法找到引用RelativeSource FindAncestor, AncestorType='System.Windows.Window', AncestorLevel='1''的绑定源.
System.Windows.Data Warning: 4 : Cannot find source for binding with reference 'RelativeSource FindAncestor, AncestorType='System.Windows.Window', AncestorLevel='1''.
我最终使用了 ArsenMkrt 方法的变体,因此接受了他的回答.但是,我仍然有兴趣找出 FindAncestor 不正常工作"的原因.
I ended up using a variation on ArsenMkrt's approach, so have accepted his answer. However, I am still interested in finding out why FindAncestor does not "just work".
推荐答案
最好的办法是给UserControl起个名字
The best way is to give a name to UserControl
在 UserControl 中创建依赖属性 MyProperty 有两种方式绑定并绑定到主窗口中,而不是像这样在 UserControl 中绑定
Create dependency property MyProperty in UserControl with two way binding and bind it in main Window, than bind in UserControl like this
<UserControl x:Name = "myControl">
<Label Content={Binding ElementName= myControl, Path=MyProperty}/>
</UserControl>
这篇关于WPF 数据绑定的“RelativeSource FindAncestor"究竟是做什么的?做?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!