临安建办网站,网站了建设,视频教学网站怎么做,北京代理记账公司招聘一个Binding有明确的数据来源 可以通过Source或ElementName赋值的方法让Binding与之关联
但是有的时候我们不能确定作为Source的对象叫什么名字#xff0c;但知道它与作为Binding目标的对象在UI上有相对关系#xff0c;比如#xff1a;空间自己关联自己的某个数据、关联自己…一个Binding有明确的数据来源 可以通过Source或ElementName赋值的方法让Binding与之关联
但是有的时候我们不能确定作为Source的对象叫什么名字但知道它与作为Binding目标的对象在UI上有相对关系比如空间自己关联自己的某个数据、关联自己某级容器的数据
这个时候我们就要使用Binding的RelativeSource属性了
看个小例子
Window x:ClassWpf.Relative6312xamlxmlnshttp://schemas.microsoft.com/winfx/2006/xaml/presentationxmlns:xhttp://schemas.microsoft.com/winfx/2006/xamlxmlns:dhttp://schemas.microsoft.com/expression/blend/2008xmlns:mchttp://schemas.openxmlformats.org/markup-compatibility/2006xmlns:localclr-namespace:Wpfmc:IgnorabledTitleRelative6312xaml Height200 Width200Grid x:Nameg1 BackgroundLightPink Margin10DockPanel x:Named1 BackgroundLightBlue Margin10Grid x:Nameg2 BackgroundLightCoral Margin10DockPanel x:Named2 BackgroundLightGreen Margin10TextBox x:NametextBox1 FontSize24 Margin10/TextBox/DockPanel/Grid/DockPanel/Grid
/Window效果图是这个样子的 把TextBox的Text属性关联到外层容器的Name属性上 在XAML中插入代码
Window x:ClassWpf.Relative6312xamlxmlnshttp://schemas.microsoft.com/winfx/2006/xaml/presentationxmlns:xhttp://schemas.microsoft.com/winfx/2006/xamlxmlns:dhttp://schemas.microsoft.com/expression/blend/2008xmlns:mchttp://schemas.openxmlformats.org/markup-compatibility/2006xmlns:localclr-namespace:Wpfmc:IgnorabledTitleRelative6312xaml Height200 Width200Grid x:Nameg1 BackgroundLightPink Margin10DockPanel x:Named1 BackgroundLightBlue Margin10Grid x:Nameg2 BackgroundLightCoral Margin10DockPanel x:Named2 BackgroundLightGreen Margin10TextBox x:NametextBox1 FontSize24 Margin10Text{Binding RelativeSource {RelativeSource FindAncestor, AncestorType{x:Type Grid},AncestorLevel1}, PathName}/TextBox/DockPanel/Grid/DockPanel/Grid
/Window效果图 也可以在窗体的构造器中创建RelativeSource的对象再进行Binding
RelativeSource FindAncestor寻找TextBox的祖宗元素
AncestorLevel 1向外层找1层
AncestorType {x: Type Grid}:寻找的类型为Grid类型