WPF combobox 解释RelativeSource

<Window x:Class="WpfApplication1.MainWindow"  
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"  
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow"  SizeToContent="WidthAndHeight">  
    <StackPanel Margin="10">  
        <ComboBox Name="comboBox"  ItemStringFormat="{}{0}秒" SelectedValue="{Binding Limit, RelativeSource={RelativeSource AncestorType=Window}}" />  
        <Button Content="" Click="Button_Click" />  
    </StackPanel>  
</Window> 

以上的combobox中  ItemStringFormat="{}{0}秒" 会在每个值后面加一个'秒'字

SelectedValue="{Binding Limit, RelativeSource={RelativeSource AncestorType=Window}}"

RelativeSource指明是相对路径来找数据源,源的类型是Window,即本xaml对应的xaml.cs中定义的数据源Limit.这里public int Limit { getset; } 

这时引申Itemsoure的指定也可是这样指定

<ComboBox x:Name="cmb" Grid.Row="0" Margin="10,8,10,8" ItemsSource="{StaticResource ec}"  SelectedValue="{Binding 可以是外层Grid的源上的字段}"/
                  DisplayMemberPath="Name" SelectedValuePath="EmpID"/>  
        <TextBlock Grid.Row="1" VerticalAlignment="Center" FontSize="18"   HorizontalAlignment="Center"  
Text="{Binding ElementName=cmb,Path=SelectedValue}"/>

 RelativeSource 属性,它通过与目标元素的关系获得相应的元素。RelativeSource的类型是RelativeSource,是一个标记扩展,有一下几种使用的方式:

1. 使源元素为目标元素本身

{Binding RelativeSource={RelativeSource self}}

2. 使源元素为目标元素的TemplatedParent属性

{Binding RelativeSource={RelativeSource TemplatedParent}}

3. 使源元素为最近的指定类型的父元素

{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type desiredType}}}

4. 使源元素为n层最近的指定类型的父元素

{Binding RelativeSource={RelativeSource FindAncestor, AncestorLevel=n, AncestorType={x:Type desiredType}}}

5. 使源元素为之前的数据绑定集合中的数据项

{Binding RelativeSource={RelativeSource PreviousData}}

在RelativeSource 中使用Self是很方便的,因为这种模式可以把该元素的一个属性绑定到另一个属性上,但却不需要为元素指定名称,比如下面这个例子,Slider的ToolTip绑定了它自己的值:

<Slider ToolTip="{Binding RelativeSource={RelativeSource Self}, Path=Value}">

 -------------------------------------------------------------------------------------------------------------------

  • RelativeSource rs = new RelativeSource();  
  • rs.Mode = RelativeSourceMode.FindAncestor;  
  • rs.AncestorLevel = 1;  
  • rs.AncestorType = typeof(Grid);  
  •   
  • Binding binding = new Binding();  
  • binding.RelativeSource = rs;  
  • binding.Path = new PropertyPath("Name");  
  • textBox1.SetBinding(TextBox.TextProperty, binding);  
  • TextBox控件向外,从最近的第一层开始寻找,找到的第一个Grid对象的Name与TextBox控件绑定 AncestorLevel属性指的是以Binding目标控件为起点的层级偏移量
  • 与之等价的XAML代码是

  • Text="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorLevel=1, AncestorType={x:Type Grid}}, Path=Name}"  

原文地址:https://www.cnblogs.com/whpepsi/p/3099395.html