什么是WPF Data Binding的“RelativeSource FindAncestor”做? [英] What exactly does WPF Data Binding's "RelativeSource FindAncestor" do?
问题描述
有谁知道为什么简单地
< Binding RelativeSource ={RelativeSource FindAncestor,AncestorType = {x:Type Window}}Path =.../>
不工作?我得到的错误信息是:
System.Windows.Data警告:4:找不到与引用'RelativeSource FindAncestor,AncestorType ='System.Windows.Window绑定的源',AncestorLevel ='1'。
编辑:我最终使用了ArsenMkrt方法的变体,所以接受了他的回答。然而,我仍然有兴趣了解为什么FindAncestor不会正常工作。
最好的方法是给出名称到UserControl
在UserControl中创建依赖关系属性MyProperty,使用双向绑定并将其绑定到主窗口中,而不是像UserControl中的绑定一样这样
< UserControl x:Name =myControl>
< Label Content = {Binding ElementName = myControl,Path = MyProperty} />
< / UserControl>
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?
Does anyone know why simply
<Binding RelativeSource="{RelativeSource FindAncestor, AncestorType={x:Type Window}}" Path="..." />
does not work? The error message I get is:
System.Windows.Data Warning: 4 : Cannot find source for binding with reference 'RelativeSource FindAncestor, AncestorType='System.Windows.Window', AncestorLevel='1''.
Edit: 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".
The best way is to give a name to 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 Data Binding的“RelativeSource FindAncestor”做?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!