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. css 图片增加模糊效果

    img{ -webkit-filter: blur(5px); -moz-filter: blur(5px); -ms-filter: blur(5px); filter: blur(5px); }

  2. 使用Python管理数据库

    使用Python管理数据库   这篇文章的主题是如何使用Python语言管理数据库,简化日常运维中频繁的.重复度高的任务,为DBA们腾出更多时间来完成更重要的工作.文章本身只提供一种思路,写的不是很全 ...

  3. Linux-PATH_环境变量

    PATH变量         是linux系统里的一个环境变量,系统已经定义好了,我们不需要再定义. 作用:         是linux里使用的命令都存在在PATH变量后面指定的目录下,我们使用命令 ...

  4. 使用Websocket框架之GatewayWorker开发电商平台买家与卖家实时通讯

    前段时间公司提了一个新的需求,在商品的详情页要实现站内买家和商品卖家实时通讯的功能以方便沟通促成交易,要开发此功能当时首先考虑到的就是swoole和workerman了,从网上大概了解了一下关于这两款 ...

  5. 转载 USB固件分析

    http://1438431234.spaces.eepw.com.cn/articles/article/item/114022 0x00000000 0x0001fff0 大小 0x1fff1 = ...

  6. UVA - 12333 字典树+大数

    思路:用字典树将前40个数字记录下来,模拟大数加法即可. AC代码 #include <cstdio> #include <cmath> #include <algori ...

  7. 关于MYCAT 读写分离,与只读事务的问题.

    习惯性为了复用mysql连接,喜欢加上@Transactional(readOnly = true) 只读事务,很多零碎的查询下,速度会快一些,也环保一些. 最近用mycat做了读写分离,其中一个查询 ...

  8. 前端日常常用git命令

    讲真,很早之前就想总结一下git常用的命令了,每次用着用着很多命令都记不住.而且我是英语渣包,有些单词慢慢靠背. git只是一个工具,我这写的只是适合我这种快速上手使用工具的小白,深究的请移步别处. ...

  9. 【前端】Vue2全家桶案例《看漫画》之番外篇、express上传漫画(可选)

    转载请注明出处:http://www.cnblogs.com/shamoyuu/p/vue_vux_app_extra_1.html 项目github地址:https://github.com/sha ...

  10. GM8180启动过程调试

    1.     burnin下的boot.s    0:    boot start        1 ;   1:    Init SMC configuration OK ;   2:    Ini ...