WPF - Data Binding入门概述

来源:互联网 发布:身份证验证算法 编辑:程序博客网 时间:2024/05/16 18:10

Data Binding是wpf特色之一,它的用法如下图:

 

 

这个图把binding的几个要素都包括了。




首先,数据来源最重要了。最方便肯定是用DataContext了,因为子节点继承了就可以直接用相应的数据了。

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


By default, bindings inherit the data context specified by the DataContext property, if one has been set.

However, the ElementName property is one of the ways you can explicitly set the source of aBinding and override the inherited data context. So do theSource andRelativeSource properties of theBinding class


DataContext强行被继承; 如果在某些地方,需要override继承来的,怎么办?你有3个选择(3者互斥,只能选一个;别贪心 :-) ):


如果是xmal中的UI控件,可以把name付给ElementName来找到这个控件,然后付给path的属性会被使用。

比如 Text="{Binding ElementName=slider1, Path=Value}"


通常用RelativeSource来指定同一个object中的binding。

This property is commonly used to bind one property of an object to another property of the same object, or to define a binding in a style or template.

如果是style或者template中,用RelativeSource来指定数据源,因为跟binding的位置有关。

     {x:Static RelativeSource.Self} or {RelativeSource Self} bind to target element.
     {RelativeSource FindAncestor, AncestorType={x:Type TypeName}} Bind to the first parent of type TypeName
     {RelativeSource FindAncestor, AncestorType={x:Type TypeName}, AnsestorLevel=n} Bind to the nth parent of type TypeName

      {RelativeSource TemplatedParent} bind to the element this template is applied to (useful in control templates, consider using TemplateBinding instead.

有时候可以用TemplateBinding来代替部分RelativeSource的binding。

A TemplateBinding is an optimized form of aBinding for template scenarios, analogous to aBinding constructed with {Binding RelativeSource={RelativeSource TemplatedParent}}.


如果是非UI的objects,那么用Source比较多。




插一句,如果要binding到一个函数上呢?ObjectDataProvider!

the ObjectDataProvider class provides functionality such as the ability to bind to the result of a method

xml数据呢?有XmlDataProvider!

To access XML data for binding using the XmlDataProvider class




更多可见如下链接:

How to: Specify the Binding Source
http://msdn.microsoft.com/en-us/library/ms746695.aspx

How to: Make Data Available for Binding in XAML
http://msdn.microsoft.com/en-us/library/ms748857.aspx


Data Binding How-to Topics

http://msdn.microsoft.com/en-us/library/ms752039.aspx


WPF Binding CheatSheet

http://www.nbdtech.com/Free/WpfBinding.pdf


Binding on a Property which is not a DependencyProperty

http://www.codeproject.com/Articles/71348/Binding-on-a-Property-which-is-not-a-DependencyPro

原创粉丝点击