WPF 如何使用RelativeSource绑定

     当一个Binding有明确的数据来源时我们可以通过为Source或者ElementName赋值的办法让binding与之关联。有些时候我们不能确定作为Source的对象叫什么名字,但知道它与作为Binding目标的对象在UI布局上有相应的关系,比如控件自己关联自己的某个属性、关联自己某级容器的数据。这时候我们就要使用Binding的RelativeSource属性。这种办法的意思是指当前元素和绑定源的位置关系。

  • 第一种关系: Self

举一个最简单的例子:在一个StackPanel中,有一个TextBlock。

<TextBlock FontSize="18" FontWeight="Bold" Margin="10"
                 Background="Red" Width="80" Height="{Binding RelativeSource={RelativeSource Self},Path=Width}">MultiBinding Sample</TextBlock>

如果想让textbox的width和height相同,通过设置属性Height="{Binding RelativeSource={RelativeSource Self},Path=Width}" 就可以实现。

还可以这样写:Height="{Binding RelativeSource={RelativeSource Mode=Self},Path=Width}",Mode是RelativeSource类的枚举。“RelativeSource Mode=Self”调用了类的枚举Mode,“RelativeSource Self”使用了类的静态属性Self,达到的目的是一样的。

 

  • 第二种关系:TemplatedParent

例如为一个Button写一个样式,修改Button为椭圆型。同时需要椭圆的背景色和Button的背景色相同。

<Style TargetType="{x:Type Button}">
            <Setter Property="Background" Value="Green"/>
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type Button}">
                        <Grid>
                            <Ellipse>
                                <Ellipse.Fill>
                                    <SolidColorBrush Color="{Binding Path=Background.Color,RelativeSource={RelativeSource TemplatedParent}}"/>
                                </Ellipse.Fill>
                            </Ellipse>
                        </Grid>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
  </Style>

在这个例子中 TemplateParent就是指的Button

  • 第三种关系:AncestorType

指定绑定源为某个父元素

<Grid>
     <Label Background = {Binding Path=Background, RelativeSource={RelativeSource AncestorType={x:Type Grid}}}/>
</Grid>

这个例子中Label的背景色和Grid的背景色一样。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值