什么是WPF Data Binding的“RelativeSource FindAncestor”做? [英] What exactly does WPF Data Binding's "RelativeSource FindAncestor" do?

查看:4027
本文介绍了什么是WPF Data Binding的“RelativeSource FindAncestor”做?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在一个WPF用户控件中工作(我的XAML文件的根元素是UserControl),我知道这是在窗口内托管的。如何使用数据绑定访问Window的属性?



有谁知道为什么简单地

 < 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆