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访问级别的,从而进行暴露数据。