WPF 绑定

时间:2015-03-06 16:08:20   收藏:0   阅读:466

WPF里分三种Binding:Binding, PriorityBindingMultiBinding,这三种Binding的基类都是BindingBase,而BindingBase又继承于MarkupExtension

Binding

提供对绑定定义的高级别访问,绑定将绑定目标对象(通常为 WPF 元素)的属性与任何数据源(例如数据库、XML 文件或包含数据的任何对象)连接起来。

常见的使用Binding的代码:
C#

Binding binding = new Binding();
// Set source object
binding.Source = treeView;
// Set source property
binding.Path = new PropertyPath("SelectedItem.Header");
// Attach to target property
currentFolder.SetBinding(TextBlock.TextProperty, binding);

XAML:

<TextBlock x:Name=”currentFolder” DockPanel.Dock=”Top”
Text=”{Binding ElementName=treeView, Path=SelectedItem.Header}”
Background=”AliceBlue” FontSize=”16”/>

所有FrameworkElement都包含SetBinding方法:SetBinding(DependencyProperty dp, String path), SetBinding(DependencyProperty dp, BindingBase binding),可以看出,FrameworkElement中的SetBinding只对DependencyProperty有效。

另一种设置Binding的方法是:BindingOperations.SetBinding(currentFolder, TextBlock.TextProperty, binding);
BindingOperations.SetBinding的原型是

public static BindingExpressionBase SetBinding(
	DependencyObject target,
	DependencyProperty dp,
	BindingBase binding
)

第一个参数是DependencyObject,所以我们可以对自定义DependencyObject或者继承自DependencyObject的类进行绑定。当然第二个参数还是DependencyProperty。

清除Binding:
BindingOperations.ClearBinding(currentFolder, TextBlock.TextProperty); //删除currentFolder上的TextBlock.TextProperty绑定
BindingOperations.ClearAllBindings(currentFolder); //删除currentFolder上的所有绑定

直接对dependency property赋值也可以解除binding, 不过只对单向binding有效。  


Bingding的源:

有三个属性用来设置源:ElementName(string)、Source(Object) 和 RelativeSource(RelativeSource)。注:这三个只能指定一个,否则异常。
ElementName: 源为一个元素(Element),这里用的是此元素中设置的Name属性。
Source:以object作为源。<TextBlock Text="{Binding Source={StaticResource myDataSource}, Path=PersonName}"/>
RelativeSource: 源相对于绑定目标的位置。
                        源是元素本身:{Binding RelativeSource={RelativeSource Self}}
                        源是Tempalte中元素的Parent:{Binding RelativeSource={RelativeSource TemplatedParent}}
                        源是绑定以collection形式的前一个数据:{Binding RelativeSource={RelativeSource PreviousData}},MSDN上关于PreviousData的说明并不多,这里有一篇文章可以参考
                        以上三项为RelativeSource中的Static值,使用这些值可以减少内存开销
                        源是Ancestor(可能比parent还高):{Binding RelativeSource={RelativeSource FindAncestor,
                                                                     AncestorLevel=n, AncestorType={x:Type desiredType}}}


Path:

Binding中的Path是 PropertyPath对象。

原文:http://www.cnblogs.com/mschen/p/4318435.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!