WPF之DataContext(转)

有时候不是你不够聪明,而是别人教给你的东西太烂!相信自己!
这是我认为,目前网络上对“DataContext”解释最好的一篇文章,跟大家分享。

What is this “DataContext” you speak of?

I frequently see new WPF users confused about what the DataContext is, and how it is used. Hopefully, this can help clarify what the DataContext is, and how it is used.

What is the DataContext?

In WPF, there are two layers to an application: the UI layer and the Data layer.

The Data layer for an application starts out as null, and you can set it using the DataContext property. All UI objects will inherit their DataContext from their parent unless you specify otherwise.

When using the Model-View-ViewModel (MVVM) Design Pattern, the DataContext (Data Layer) is your application, while UI objects, like Buttons, Labels, DataGrids, and even Windows, are all just user-friendly items that allow a user to easily interact with the DataContext, which is your actual application and is typically comprised of ViewModels and Models.

How is it used

Whenever you do a basic binding in WPF, you are binding to the DataContext.

For example, when you write

<Label Name="myLabel" Content="{Binding Path=Name}" />

you are binding to myLabel.DataContext.Name, and not to myLabel.Name.

Other binding properties, such as ElementName or RelativeSource, can be used to tell the binding to lookup the property in something other than the current DataContext.

An Example

Lets start with a regular Window. Without setting the DataContext, the window still displays but there is no data behind it.

<Window x:Name="MyWindow" ...>
   ...
</Window>

Now suppose we set the DataContext to an object of type ClassA in the code-behind when this Window initializes:

public partial class MyWindow: Window
{
    public MyWindow()
    {
       InitializeComponent();
       this.DataContext = new ClassA();
    }
}

Now the data layer behind that the Window is an object of type ClassA.

If ClassA has a property called Name, I could add a Label to the window and bind it to Name property of the DataContext, and whatever value is stored in ClassA.Name would get displayed.

<Window x:Name="MyWindow" ...>
   <Label Content="{Binding Name}" />
</Window>

Now, suppose ClassA has a property called ClassB, and both classes have a property called Name. Here is a block of XAML which illustrates how the DataContext works. It also includes an example of how a control would refer to a property not in its own DataContext.

<!-- DataContext set to ClassA in initialization code -->
<Window x:Name="MyWindow">
 
    <!-- DataContext here is not specified, so it's inherited
         from its parent's DataContext, which is ClassA -->
    <StackPanel>
 
        <!-- DataContext inherited from parent, which is
             ClassA, so this will display ClassA.Name -->
        <Label Content="{Binding Name}" />
 
         <!-- DataContext is still ClassA, however we are
              setting it to ClassA.ClassB with a binding -->
        <StackPanel DataContext="{Binding ClassB}">
 
            <!-- DataContext inherited from parent, which is
                 ClassB, so this will display ClassB.Name -->
            <Label Content="{Binding Name}" />
 
            <!-- DataContext is still ClassB, but we are
                 binding to the Window's DataContext.Name,
                 which is 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>

As you can see, all the basic bindings look for their value in the data layer (DataContext) of the UI object

Summary

So to summarize, WPF applications have two layers: the UI layer and the Data layer. The data layer for an application starts out as null, and can be set using the DataContext property. UI objects without a DataContext set will inherit their data layer from their parent object. Bindings are used to look up values in the data layer, and display them in the UI layer.

When using the MVVM design pattern, the data layer is your application, while the UI layer just provides a user-friendly way to access the Data layer.

What is this “DataContext” you speak of?

I frequently see new WPF users confused about what the DataContext is, and how it is used. Hopefully, this can help clarify what the DataContext is, and how it is used.

What is the DataContext?

In WPF, there are two layers to an application: the UI layer and the Data layer.

The Data layer for an application starts out as null, and you can set it using the DataContext property. All UI objects will inherit their DataContext from their parent unless you specify otherwise.

When using the Model-View-ViewModel (MVVM) Design Pattern, the DataContext (Data Layer) is your application, while UI objects, like Buttons, Labels, DataGrids, and even Windows, are all just user-friendly items that allow a user to easily interact with the DataContext, which is your actual application and is typically comprised of ViewModels and Models.

How is it used

Whenever you do a basic binding in WPF, you are binding to the DataContext.

For example, when you write

<Label Name="myLabel" Content="{Binding Path=Name}" />

you are binding to myLabel.DataContext.Name, and not to myLabel.Name.

Other binding properties, such as ElementName or RelativeSource, can be used to tell the binding to lookup the property in something other than the current DataContext.

An Example

Lets start with a regular Window. Without setting the DataContext, the window still displays but there is no data behind it.

<Window x:Name="MyWindow" ...>
   ...
</Window>

Now suppose we set the DataContext to an object of type ClassA in the code-behind when this Window initializes:

public partial class MyWindow: Window
{
    public MyWindow()
    {
       InitializeComponent();
       this.DataContext = new ClassA();
    }
}

Now the data layer behind that the Window is an object of type ClassA.

If ClassA has a property called Name, I could add a Label to the window and bind it to Name property of the DataContext, and whatever value is stored in ClassA.Name would get displayed.

<Window x:Name="MyWindow" ...>
   <Label Content="{Binding Name}" />
</Window>

Now, suppose ClassA has a property called ClassB, and both classes have a property called Name. Here is a block of XAML which illustrates how the DataContext works. It also includes an example of how a control would refer to a property not in its own DataContext.

<!-- DataContext set to ClassA in initialization code -->
<Window x:Name="MyWindow">
 
    <!-- DataContext here is not specified, so it's inherited
         from its parent's DataContext, which is ClassA -->
    <StackPanel>
 
        <!-- DataContext inherited from parent, which is
             ClassA, so this will display ClassA.Name -->
        <Label Content="{Binding Name}" />
 
         <!-- DataContext is still ClassA, however we are
              setting it to ClassA.ClassB with a binding -->
        <StackPanel DataContext="{Binding ClassB}">
 
            <!-- DataContext inherited from parent, which is
                 ClassB, so this will display ClassB.Name -->
            <Label Content="{Binding Name}" />
 
            <!-- DataContext is still ClassB, but we are
                 binding to the Window's DataContext.Name,
                 which is 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>

As you can see, all the basic bindings look for their value in the data layer (DataContext) of the UI object

Summary

So to summarize, WPF applications have two layers: the UI layer and the Data layer. The data layer for an application starts out as null, and can be set using the DataContext property. UI objects without a DataContext set will inherit their data layer from their parent object. Bindings are used to look up values in the data layer, and display them in the UI layer.

When using the MVVM design pattern, the data layer is your application, while the UI layer just provides a user-friendly way to access the Data layer.

WPF之DataContext(转)的更多相关文章

  1. WPF之DataContext

    1. 继承属性: DataContext is a property on FrameworkElement (base class for all WPF Controls) and is impl ...

  2. [WPF] How to bind to data when the datacontext is not inherited

    原文:[WPF] How to bind to data when the datacontext is not inherited 原文地址:http://www.thomaslevesque.co ...

  3. WPF入门(1)——DataContext

    在WPF中,应用程序有两层:UI层和Data层.这里新建一个项目说明哪些是UI层,哪些是数据层. UI层很明显,就是用户看到的界面.但是数据层并不是下图所示: 上图中是UI层view的后台代码.当然, ...

  4. 【我们一起写框架】MVVM的WPF框架(二)—绑定

    MVVM的特点之一是实现数据同步,即,前台页面修改了数据,后台的数据会同步更新. 上一篇我们已经一起编写了框架的基础结构,并且实现了ViewModel反向控制Xaml窗体. 那么现在就要开始实现数据同 ...

  5. [No000012E]WPF(6/7):概念绑定

    WPF 的体系结构,标记扩展,依赖属性,逻辑树/可视化树,布局,转换等.今天,我们将讨论 WPF 最重要的一部分——绑定.WPF 带来了优秀的数据绑定方式,可以让我们绑定数据对象,这样每次对象发生更改 ...

  6. 关于WPF中ItemsControl系列控件中Item不能继承父级的DataContext的解决办法

    WPF中所有的集合类控件,子项都不能继承父级的DataContext,需要手动将绑定的数据源指向到父级控件才可以. <DataGridTemplateColumn Header="操作 ...

  7. WPF设置Window的数据上下文(DataContext)为自身

    WPF设置Window的数据上下文(DataContext)为自身的XAML: DataContext="{Binding RelativeSource={RelativeSource Se ...

  8. WPF中 ItemsSource 和DataContext不同点

    此段为原文翻译而来,原文地址 WPF 中 数据绑定 ItemSource和 DataContext的不同点: 1.DataContext 一般是一个非集合性质的对象,而ItemSource 更期望数据 ...

  9. WPF学习笔记——DataContext 与 ItemSource

    作为一个WPF新手,在ListBox控件里,我分不清 DataContext 与 ItemSource的区别. 在实践中,似乎: <ListBox x:Name="Lst" ...

随机推荐

  1. 洛谷P1854 花店橱窗布置 分析+题解代码

    洛谷P1854 花店橱窗布置 分析+题解代码 蒟蒻的第一道提高+/省选-,纪念一下. 题目描述: 某花店现有F束花,每一束花的品种都不一样,同时至少有同样数量的花瓶,被按顺序摆成一行,花瓶的位置是固定 ...

  2. python3基础入门-知识点简记

    1.基础语法 编码.标识符.保留字.注释.行与缩进... 2.变量类型 (1)Python3有6个标准的数据类型: Numbers(数字)  数字数据类型用于存储数值  不可改变的数据类型 可细分为  ...

  3. Spring Boot : Whitelabel Error Page解决方案

    楼主最近爱上了一个新框架--Spring Boot, 搭建快还不用写一堆xml,最重要的是自带Tomcat 真是好 pom.xml <?xml version="1.0" e ...

  4. 拦截窗体关闭、最大、最小事件 - Winform

    RT,不赘述,代码以下: const int WM_SYSCOMMAND = 0x112; const int SC_CLOSE = 0xF060; const int SC_MINIMIZE = 0 ...

  5. Linux下添加自定义脚本到开机自启动,标准rpm,举例:设置Apache自启动

    写一个脚本,名字为:autostart.sh,放在/etc/init.d/目录下,赋予权限chmod +x /etc/init.d/autostart.sh 代码如下 #!/bin/sh #chkco ...

  6. ES6的介绍和常用语法

    本文最初发表于博客园,并在GitHub上持续更新前端的系列文章.欢迎在GitHub上关注我,一起入门和进阶前端. 以下是正文. 前言 ECMAScript 是 JS 的语言标准.而 ES6 是新的 J ...

  7. OpenStack Ironic 常见问题

    whole disk和partition 镜像 whole disk镜像部署可以支持windows,但是不能自定义分区(可以通过cloud-init实现),分区表是做镜像的人确定好的,partitio ...

  8. Ubuntu12.04LTS安装好后是空白桌面的解决步骤(更新显卡驱动)

    安装完毕启动后,明显慢的要死,登陆后竟然是一个空白的桌面环境,Ctrl+Alt+T 根本没有任何反应.唯一的反应就是右键能够创建文件和文档. 同时打开的窗口没有最大化,最小化及关闭按钮. GOOGLE ...

  9. freemarker报错之十四

    1.错误描述 <html> <head> <meta http-equiv="content-type" content="text/htm ...

  10. (十四)java中super和this

    super代表的是父类.超类,用在继承中的子类中:this代表对象本身,用在本类中.     super访问的是被子类隐藏的父类的属性或被覆盖的方法,而this访问的是同一类中的成员.     sup ...