wpf - bind to self, parent or sibling

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>
 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值