wpf - bind to self, parent or sibling

3167 단어 WPF
It is very common that you may use your self as the data context, and you have some controls in the class that bind to data of the containing class.
 

Bind to Parent 


 
There are so many way to achieve this
 
1. in the constructor , set this.DataContext = this;
 
 
 
public MyUserControl(){

   this.DataContext = this;  
}
 
 
2. give the control in xaml a name and bind with ElementName attribute
 
 
 
<UserControl x:Class=MyUserControl
   x:Name="Self"
>
  <WrapPanel>
     <TextBox Text="{Binding Path=MyDp, ElementName=Self"} />
  </WrapPanel>
</UserControl>

 
 
3. Use relative source markup extension, and use AncestorType Attribute
 
 
<UserControl x:Class=MyUserControl
>
  <WrapPanel>
    <TextBox Text="{Binding Path=MyDp, Mode=TwoWay,RelativeSource={RelativeSource AncestorType=UserControl}}" />
  </WrapPanel>
</UserControl>

 
 
Or you can be more specific
 


<UserControl x:Class=MyUserControl
  xmlns:views="MyUserControl"
>
  <WrapPanel>
    <TextBox Text="{Binding Path=MyDp, Mode=TwoWay,RelativeSource={RelativeSource AncestorType={x:Type views:MyUserControl}}}" />
  </WrapPanel>
</UserControl>
 
 
 
4. it is similar to 3, except if there are more than ancestor type in the hierarchy, so you want to confine a level to search .
 
 
 

<UserControl x:Class=MyUserControl
>
  <WrapPanel>
    <TextBox Text="{Binding Path=MyDp, Mode=TwoWay,RelativeSource={RelativeSource AncestorType=UserControl, AncestorLevel=2}}" />
  </WrapPanel>
</UserControl>
 

Bind to self


 
To bind to self, there is two way 
 
 
1. with RelativeSource, Mode=Self
 
 
<TextBox Text="{Binding Path=Background, Mode=TwoWay,RelativeSource={RelativeSource Self}}"  />
 
 
2 with ElementName and assign a name to 'self'
 
<TextBox Text="{Binding Path=Background, Mode=TwoWay, ElementName=self}" x:Name="self" />

 
 

Bind to sibling.


 
 
There is no easy way to do that, however, you can take ciruitous way, with the help of finding the parent/self, and then walk down.
 
    <StackPanel>
        <views:UserControl1 />
        <views:UserControl2 />
        <TextBox Text="{Binding Path=Parent.Children[0].MyDp, Mode=TwoWay, RelativeSource={RelativeSource Self}}" />
    </StackPanel>
 
 
 

좋은 웹페이지 즐겨찾기