WPF之DataContext(转)

news/2024/7/7 14:32:50
有时候不是你不够聪明,而是别人教给你的东西太烂!相信自己!
这是我认为,目前网络上对“DataContext”解释最好的一篇文章,跟大家分享。
原文地址:https://rachel53461.wordpress.com/2012/07/14/what-is-this-datacontext-you-speak-of/

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.

转载于:https://www.cnblogs.com/igotogo/p/5478223.html


http://www.niftyadmin.cn/n/3027600.html

相关文章

替换XP的系统字体为Vista的Segoe UI字体的较完美方法

看到园中有人将Vista的Segoe UI字体放出了&#xff0c;我马上想到了能不能将Segoe UI字体集成到WinXP中&#xff0c;最佳的结果无疑是可以平滑的替换英文系统字体&#xff0c;但到底如何做呢&#xff1f;有一篇正体字的blog有所提到替换系统字体&#xff0c;说干就干&#xff0…

敏捷开发团队管理系列之五 大型研发团队的切分(刚参加3 17 MDP团队管理场次的读者请看)

本文是团队管理系列的第五篇&#xff0c;也是“松结对编程”系列的第九篇。&#xff08;团队管理栏目目录&#xff0c;松结对编程栏目目录&#xff09;抱歉在这次MPD上不知道中间的20分钟茶歇也在3小时内&#xff0c;所以最后有10分钟左右的内容没有讲&#xff0c;这里补充一下…

《Microsoft Office SharePoint Server 2007 前瞻技术指南》第一章预览

《SharePoint Portal Server 2003 深入指南》预计在七月份就出版了&#xff0c;希望尽早能够出现在各个网上书店。 我已经开始计划写一本Office SharePoint Server 2007的技术书籍了&#xff0c;暂定名称是《Microsoft Office SharePoint Server 2007 前瞻技术指南》。我希望能…

敏捷开发产品管理系列之八 基于业务设计技术架构(兼谈12306性能问题)

本文是敏捷开发产品管理系列的第八篇。&#xff08;专栏目录&#xff09;在产品开发中&#xff0c;常常遇到产品性能问题&#xff0c;这些性能问题会很大程度上影响到产品的架构。但解决这些性能问题&#xff0c;切莫认为只是技术人员的事情&#xff0c;产品经理和产品总监也要…

[新功能]通过作者名访问Blog

有时你也许会只记得某个Blog的作者名&#xff0c;而忘记了Blog地址&#xff0c;遇到这样的情况&#xff0c;我通常是通过Google站内搜索找到作者的Blog&#xff0c;这样不是很方便。现在你可以直接通过作者名访问Blog&#xff0c;比如&#xff1a; http://www.cnblogs.com/博客…

IT职场人生系列之十三 技术 管理 业务

本文是IT职场人生系列的第十三篇。很多技术人员工作几年后&#xff0c;都要面临未来的出路问题。所有出路中&#xff0c;无外乎技术、管理、业务三个层面。技术技术本身也是一条出路&#xff0c;但是在之十二中曾经提到&#xff0c;有深技术和浅技术两者之分。如果本来是从事浅…

[转]ASP.NET中如何防范SQL注入式攻击

一、什么是SQL注入式攻击&#xff1f; 所谓SQL注入式攻击&#xff0c;就是攻击者把SQL命令插入到Web表单的输入域或页面请求的查询字符串&#xff0c;欺骗服务器执行恶意的SQL命令。在某些表单中&#xff0c;用户输入的内容直接用来构造&#xff08;或者影响&#xff09;动态S…

IT职场人生系列之二 大学生活

本文是IT职场人生系列的第二篇。本人本来小学至高中一帆风顺&#xff0c;没想到自大学以后颇多坎坷&#xff0c;最近家族中有位下一代来咨询考大学的事情&#xff0c;也算是帮我重新整理了一下思路。先做个总结&#xff1a;大学成绩马马虎虎&#xff0c;但在班里也算是前5&…