码迷,mamicode.com
首页 > Windows程序 > 详细

wpf 数据绑定1

时间:2014-10-10 15:43:53      阅读:269      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   io   使用   ar   数据   sp   div   

数据绑定实质上就是把一些任意的.net对象绑定到一起。那么绑定的源头就有1.绑定到目标对象的属性(通常为wpf元素)2.其他任何数据源

    数据绑定的关键是System.Windows.Data.Binding类,他会把两个属性粘在一起,并在他们之间建立一条通信通道

            Binding binding = new Binding();
            //设置源对象
            binding.Source = tree;
            //设置源属性
            binding.Path = new PropertyPath("SelectedItem.Header");
            //添加到目标属性
            //currentName.SetBinding(TextBlock.TextProperty, binding);
            BindingOperations.SetBinding(currentName, TextBlock.TextProperty, binding);

   绑定有源属性好目标属性两个概念。所谓的源属性是通过两步来实现的。 设置源对象给binding的Source属性==》并把与他相关联的属性的名字通过一个propertyPath实例传递给Path属性。将binding与目标属性相关联,可以调用FrameworldElements对象的SetBinding方法。(在这个方法的内部好像是调用了BindingOperations.SetBinding方法),这样就有了上面代码中两种将binding添加到目标属性的方式。

   使用xaml添加binding的方式如下代码所示:

        <TextBlock Text="{Binding ElementName=tree,Path=SelectedItem.Header}"></TextBlock>

注意在xaml中不是使用Source属性来来设置源对象的,而是使用ElementName来设置,同样可以使用Source属性来设置源对象。

        <TextBlock Text="{Binding Source={StaticResource tree},Path=SelectedItem.Header}"></TextBlock>

   绑定的移除:

   如果一个绑定在软件的生命周期内已经没用了,可以通过BindingOperation.ClearBinding方法来移除绑定。

BindingOperations.ClearBinding(currentName,TextBlock.TextProperty);
//移除某个控件的单个属性绑定
BindingOperations.ClearBinding(currentName);
//移除某个控件的所有属性的绑定
//同样为控件赋值也会移除绑定,但是这种情况仅能清除单项绑定

能够获取Binding源的属性:

  1. ElementName(string)

      源为一个元素,Name为此元素的name属性。

  2. Source(Object)

  3. RelativeSource(RelativeSource)

       它通过与目标元素的关系获得相应的元素。

     使源元素为目标元素本身:{Binding RelativeSource={RelativeSource self}}

     使源元素为目标元素的TemplateParent属性: {Binding RelativeSource={RelativeSource TemplateParent}}...还有几种方式,现在还不能过理解等之后再去理解。

绑定的源为普通.net属性

     使用.net属性作为源的时候,如果Source发生了变化但是在wpf的UI上是不会显示变化的。最好是使用INotifyPropertyChanged接口,该接口有一个PropertyChanged事件。当然INotifyPropertyChanged接口是针对单个类的,如果针对集合可以使用ObservableCollection<>这个集合类。

    

wpf 数据绑定1

标签:style   blog   color   io   使用   ar   数据   sp   div   

原文地址:http://www.cnblogs.com/someoneHan/p/4015629.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!