您的位置:首页 > 其它

WPF中的binding(九)- 使用Binding的RelativeSource

2016-06-29 07:54 344 查看
我们进行Bingding时,如果明确知道数据源的Name,就能用Source或者ElementName进行绑定,但是有时候我们需要绑定的数据源可能没有明确的Name,此时我们就需要利用Bingding的RelativeSource进行绑定。

一、控件关联自身的属性

<Window x:Class="_6_27.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid x:Name="g1" Background="Red" Margin="10">
<DockPanel Name="d1" Background="Orange" Margin="10">
<Grid x:Name="g2" Background="Yellow" Margin="10">
<DockPanel Name="d2" Background="LawnGreen" Margin="10">
<TextBox Name="textbox" FontSize="24" Margin="10"
Text="{Binding RelativeSource={RelativeSource Mode=Self},Path=Name}"/>
</DockPanel>
</Grid>
</DockPanel>
</Grid>
</Window>

关联控件本身的属性时,只需要设置RelativeSource的Mode=Self即可。

其等效的cs代码:

RelativeSource rs = new RelativeSource();
rs.Mode = RelativeSourceMode.Self;
Binding binding = new Binding("Name") { RelativeSource = rs };
this.textbox.SetBinding(TextBox.TextProperty, binding);

运行效果如下:



二、控件关联其父级容器的属性

<Window x:Class="_6_27.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid x:Name="g1" Background="Red" Margin="10">
<DockPanel Name="d1" Background="Orange" Margin="10">
<Grid x:Name="g2" Background="Yellow" Margin="10">
<DockPanel Name="d2" Background="LawnGreen" Margin="10">
<TextBox Name="textbox" FontSize="24" Margin="10"
Text="{Binding RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type Grid},AncestorLevel=1},Path=Name}"/>
</DockPanel>
</Grid>
</DockPanel>
</Grid>
</Window>

RelativeSource属性的数据类型为RelativeSource类,AncestorLevel指的是以Bingding目标控件为起点的层级偏移量,d2的偏移量是1,g2的偏移量是2,AncestorType指的是要找的目标对象的类型。值得注意的是AncestorLevel需要参考AncestorType使用,如上面设置了AncestorType={x:Type Grid},则Bingding在寻找时会忽略非Grid的控件,此时g2的偏移量是1,g1的偏移量是2,DockPanel被忽略。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: