Binding源之DataContext——没有Source的Binding

1.DataContext概述:

DataContext属性被定义在FameworkElement类里,这个类是WPF控件的基类,因此,所有WPF控件都具备这个属性。WPF的UI布局是树形结构,这棵树的每个节点都是控件,因此,在UI元素树的每个节点都有DataContext。当一个Binding只知道自己的Path而不知道Source时,那么,距离Binding最近的节点的DataContext会向下传递,如果这个节点的DataContext具有Path指定的属性,Binding会将这个对象作为自己的Source,如果没有,那么距离增加,继续传递,如果所有的节点的DataContext的属性都不满足,则这个Binding就没有Source。

2.简单实例:

首先,创建一个Student类,具有Id,Name,Age三个属性:

    class Student
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public int Age { get; set; }
    }

然后在Xaml创建程序UI:

<Window x:Class="BindingInstance1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:BindingInstance1"
        mc:Ignorable="d"
        Title="MainWindow" Height="135" Width="300">
    <StackPanel Background="LightBlue">
        <StackPanel.DataContext>
            <local:Student Id="6" Age="29" Name="Tim"/>
        </StackPanel.DataContext>
        <StackPanel>
            <!--未绑定Source,找到上级的StackPanel.DataContext,发现属性值匹配,那么Source为Student-->
            <TextBox Text="{Binding Id}" Margin="5"/>   
            <TextBox Text="{Binding Age}" Margin="5"/>
            <TextBox Text="{Binding Name}" Margin="5"/>
        </StackPanel>
    </StackPanel>
</Window>

运行效果:

 UI布局图:

 

3.使用技巧:

(1)当UI上的多个控件都使用Binding关注同一对象时,不妨使用DataContext。

(2)当作为Source的对象不能被直接访问时,比如源控件是private访问级别,可以使用DataContext,这个属性是public访问级别的,从而进行暴露数据。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值