WPF中DataContext作用


最近在学习WPF绑定的时候不明白DataContext的作用,经常导致数据绑定不上问题。

1,WPF应用程序有UI层和数据层,通过DataContext连接。

     

 需要注意的是View类的C#代码,并不是数据层。

2,未设置DataContext的UI对象将从其父对象继承其数据层


<Window x:Name="MyWindow"> 
    
    <StackPanel> 
        
        <Label Content="{Binding Name}" />
         
        <StackPanel DataContext="{Binding ClassB}"> 
            
            <Label Content="{Binding Name}" />
            
            <Label Content="{Binding 
                       ElementName=MyWindow, 
                       Path=DataContext.Name}" /> 
        StackPanel> 
        
        <Label Content="{Binding ClassB.Name}" />
    StackPanel>
Window>

3,为UI层指定DataContext的两种方式。

一种是在View后台中:

var cont = new MainViewModle();
DataContext = cont;

一种是在XAML中:


<UserControl.Resources>
    <vm:CalculatorViewModel x:Key="calculatorVM" />
UserControl.Resources>

以上内容源自以下资料

https://www.cnblogs.com/feipeng8848/p/11637108.html

--------------------------------------------

本人所写博客仅为记录个人在学习过程中遇到的问题,如有错误造成误导,还请见谅。