WPF入门(1)——DataContext

在WPF中,应用程序有两层:UI层和Data层。这里新建一个项目说明哪些是UI层,哪些是数据层。

UI层很明显,就是用户看到的界面。但是数据层并不是下图所示:

上图中是UI层view的后台代码。当然,你可以使用事件的方式把所有的业务逻辑代码写到这里,但是我们采用MVVM的时候业务逻辑是与这里解耦的,数据层是DataContext,此时并没有指定。
接下来我们新建个目录,然后添加个类文件:

然后指定VM类为DataContext:

此时我们才算为MVVM模式的wpf应用程序创建了数据层,也就是MainViewModel类。

默认,应用程序的数据层(DataContext)是null,我们可以使用DataContext属性对其进行设置。
除非另行指定,否则所有UI对象都将从其父对象继承其DataContext。
实际上DataContext才算是我们的实际应用程序(业务逻辑),他通常由ViewModels和Models组成。
UI对象(如按钮,标签,DataGrids甚至Windows)实际作用是允许用户轻松与DataContext交互。
当你写<Label Name="myLabel" Content="{Binding Path=Name}" />你是绑定到myLabel.DataContext.Name,而不是myLabel.Name。

<!-- 注意此时我已经在初始化代码中设置DataContext 为 ClassA,DataContext = new ClassA  -->
<Window x:Name="MyWindow"> 
 
    <!-- DataContext 没有被指定,所以继承自父类
         的 DataContext,也就是 ClassA -->
    <StackPanel> 
 
        <!-- DataContext 继承自父类,也就是 
             ClassA, 所以这里会显示 ClassA.Name -->
        <Label Content="{Binding Name}" />
 
         <!-- DataContext 仍然是ClassA, 但是我们通过binding设置为ClassA.ClassB-->
        <StackPanel DataContext="{Binding ClassB}">
 
            <!-- DataContext 继承自父类,也就是ClassB,所以这里会显示 ClassB.Name -->
            <Label Content="{Binding Name}" />
 
            <!-- DataContext i仍然是 ClassB, 但是我们binding 到了Window's DataContext.Name, 也就是 ClassA.Name -->
            <Label Content="{Binding 
                       ElementName=MyWindow, 
                       Path=DataContext.Name}" /> 
        </StackPanel>
 
        <!-- We've left the StackPanel with its DataContext 
             bound to ClassB, so this Label's DataContext 
             is ClassA (inherited from parent StackPanel), 
             and we are binding to ClassA.ClassB.Name -->
        <Label Content="{Binding ClassB.Name}" />
    </StackPanel>
</Window>

所有基本绑定都在UI对象的数据层(DataContext)中寻找它们的值。
综上所述,WPF应用程序具有两层:UI层和数据层。应用程序的数据层以null开头,可以使用DataContext属性设置。未设置DataContext的UI对象将从其父对象继承其数据层。绑定用于在数据层中查找值,并在UI层中显示它们。
使用MVVM设计模式时,数据层是您的应用程序,而UI层只是提供了一种用户友好的方式来访问数据层。

datacontext的绑定
可以在view的后台代码中手动指定例如在构造函数中:

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

另外也可以写到资源中,首先需要写一个viewmodel类:

public MainViewModel()
{
    plusCommand = new PlusCommand(this);
}

然后把vm类放到资源中:

<!--需要指定名称空间vm:
xmlns:vm="clr-namespace:SimpleCommandDemoApp.ViewModels"-->
<UserControl.Resources>
    <vm:CalculatorViewModel x:Key="calculatorVM" />
</UserControl.Resources>

最后就可以在xaml中指定了:

DataContext="{Binding Source={StaticResource calculatorVM}}"

WPF使用DataContext将数据层与UI层实现了解耦,那么他们之间是如何交互的?实际上上面已经略有涉猎,那就是Binding,上面实例的ClassA、ClassB的Name就是通过Binding来展示到UI上的,详细介绍在下一篇文章中再做说明。

工程源代码上传在GitHub上了:https://github.com/feipeng8848/WPF-Demo

参考:https://rachel53461.wordpress.com/2012/07/14/what-is-this-datacontext-you-speak-of/

posted @ 2019-10-08 18:19  feipeng8848  阅读(21572)  评论(0编辑  收藏  举报