标签:tor ali 概述 sof namespace res element efi font
一、概述
当Binding有明确的数据来源的时候,我们可以用Source或者ElementName赋值的办法让Binding与之关联。
但是,有时候当我们不能确定作为Source的对象叫什么名字的时候,但我们知道它与作为Binding目标的对象在UI布局上的对应关系的时候,我们就
需要使用Binding的RelativeSource属性了。
二、例子
以下例子演示了使用Binding的RelativeSource属性来绑定父级容器的Name属性以及控件本身的Name属性。
1 <Window x:Class="BindingDemo3XmlDataSource.MainWindow" 2 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 3 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 4 xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 5 xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 6 xmlns:local="clr-namespace:BindingDemo3XmlDataSource" 7 mc:Ignorable="d" 8 Title="BindingDemo3RelativeSource" Height="350" Width="525"> 9 <Grid x:Name="g1" Margin="10" Background="Red"> 10 <DockPanel x:Name="d1" Margin="10" Background="Pink" > 11 <Grid x:Name="g2" Margin="20" Background="Green" > 12 <DockPanel x:Name="d2" Margin="10" Background="PaleVioletRed" > 13 <Grid x:Name="g3" Margin="10" Background="Red"> 14 <Grid x:Name="g4" Margin="10" Background="Green"> 15 <Grid.RowDefinitions> 16 <RowDefinition Height="*"/> 17 <RowDefinition Height="*"/> 18 <RowDefinition Height="*"/> 19 </Grid.RowDefinitions> 20 <TextBox Background="AliceBlue" 21 Text="{Binding RelativeSource={RelativeSource Mode=FindAncestor,AncestorLevel=4,AncestorType={x:Type Grid}}, Path=Name}" 22 FontSize="22" FontWeight="Bold" TextAlignment="Center"> 23 24 25 </TextBox> 26 <TextBox Grid.Row="1" Background="Silver" 27 Text="{Binding RelativeSource={RelativeSource Mode=FindAncestor,AncestorLevel=1,AncestorType={x:Type DockPanel}}, Path=Name}" 28 FontSize="22" FontWeight="Bold" TextAlignment="Center"> 29 30 </TextBox> 31 <TextBox Grid.Row="2" Background="AliceBlue" Name="TextBox1" 32 Text="{Binding RelativeSource={RelativeSource Mode=Self}, Path=Name}" 33 FontSize="22" FontWeight="Bold" TextAlignment="Center"> 34 35 </TextBox> 36 </Grid> 37 </Grid> 38 </DockPanel> 39 </Grid> 40 </DockPanel> 41 </Grid> 42 </Window>
部分等价的C#代码参考以下:
RelativeSource rs = new RelativeSource();
rs.Mode = RelativeSourceMode.Self;
Binding binding = new Binding("Name") {RelativeSource = rs };
this.TextBox1.SetBinding(TextBox.TextProperty, binding);
结果如下:
标签:tor ali 概述 sof namespace res element efi font
原文地址:https://www.cnblogs.com/3xiaolonglong/p/9766356.html