深入浅出WPF 第二部分(9)

本文详细介绍了在WPF中使用RelativeSource属性进行控件间基于相对位置的绑定方法,包括同一级控件之间的绑定、关联控件本身及父级容器的数据。通过实例展示了如何灵活运用RelativeSource实例实现复杂的数据绑定需求。

6.3.12 使用Binding的RelativeSource

同一级控件知道名字前提下的绑定:

    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition />
            <RowDefinition />
        </Grid.RowDefinitions>
        <TextBox x:Name="textBox1" Grid.Row="0" Margin="5"/>
        <TextBox x:Name="textBox2" Grid.Row="1" Margin="5" Text="{Binding ElementName=textBox1, Path=Text, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
    </Grid>

有些时候我们不能确定作为Source的对象叫什么名字,但知道它与作为Binding目标的对象在UI布局上有相对关系,比如控件自己关联自己的某个数据,关联自己某级容器的数据。这时候我们就要使用Binding的RelativeSource属性。

    <Grid x:Name="g1" Background="Orange" Margin="10">
        <DockPanel x:Name="d1" Background="Yellow" Margin="10">
            <Grid x:Name="g2" Background="LawnGreen" Margin="10">
                <TextBox x:Name="textBox1" Margin="10"/>
            </Grid>
        </DockPanel>
    </Grid>

            textBox1.SetBinding(TextBox.TextProperty, new Binding("Background")
            {
                RelativeSource = new RelativeSource(RelativeSourceMode.FindAncestor, typeof(DockPanel), ancestorLevel: 1)
            });

    <Grid x:Name="g1" Background="Orange" Margin="10">
        <DockPanel x:Name="d1" Background="Yellow" Margin="10">
            <Grid x:Name="g2" Background="LawnGreen" Margin="10">
                <TextBox x:Name="textBox1" Margin="10" 
                         Text="{Binding Path=Background, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type Grid}, AncestorLevel=2}}"/>
            </Grid>
        </DockPanel>
    </Grid>

也可以关联控件本身自己,只要让Mode属性值设置为Self。

    <Grid x:Name="g1" Background="Orange" Margin="10">
        <DockPanel x:Name="d1" Background="Yellow" Margin="10">
            <Grid x:Name="g2" Background="LawnGreen" Margin="10">
                <TextBox x:Name="textBox1" Margin="10" 
                         Text="{Binding Path=Name, RelativeSource={RelativeSource Mode=Self}}"/>
            </Grid>
        </DockPanel>
    </Grid>


RelativeSource实例:

            <TextBox Text="{Binding RelativeSource={RelativeSource AncestorLevel=1, AncestorType={x:Type Window},Mode=FindAncestor}, Path=.Height}" Width="100" Height="50"/>
            <TextBox Text="{Binding RelativeSource={RelativeSource AncestorLevel=1, AncestorType={x:Type Window},Mode=FindAncestor}, Path=.Width}" Width="100" Height="50"/>


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值