WPF之Binding基础四 使用DataContext作为Binding的源

来源:互联网 发布:花千骨网络视频 编辑:程序博客网 时间:2024/05/16 05:49

在WPF里面,FrameworkElement是WPF控件的基类,而DataContext属性就被定义在这个类里面,所以说所有的WPF控件都有这个属性。WPF的UI是树状的,每个节点都是控件,所以每个节点都有DataContext属性。如果一个Binding找不到自己的Source那他就会沿着这个UI树一直往上找,直到找到和Path对应的那个属性,如果到最外层也没找到,那就没有数据源。

XMAL代码

<Window x:Class="使用DataContext作为Binding的源.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:使用DataContext作为Binding的源"
Title="MainWindow" Height="350" Width="525">
<StackPanel Background="LightBlue">
<StackPanel.DataContext>
<local:User Name="lj"/>
</StackPanel.DataContext>
<Grid>
<StackPanel>
<TextBox Text="{Binding Path=Name}" Margin="5"/>
</StackPanel>
</Grid>
</StackPanel>

</Window>

User类

class User
{
public string Name
{
get; set;
}
}


<script type="text/javascript"><!--google_ad_client = "ca-pub-1944176156128447";/* cnblogs 首页横幅 */google_ad_slot = "5419468456";google_ad_width = 728;google_ad_height = 90;//--></script><script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>
原创粉丝点击