美文网首页
c#笔记之3(WPF Databinding Part 2)

c#笔记之3(WPF Databinding Part 2)

作者: 沉云落雨 | 来源:发表于2017-11-26 18:58 被阅读0次

上篇文章说到,简单binding只能反映List的Add和Remove操作。如果想要所有变化显示出来,必须使用ObservableCollection来代替List,同时把类继承于INotifyPropertyChanged来让控件了解到Collection中每个对象的属性发生变化。
首先在Main.cs里把List改成ObservableCollection。

// Main.cs
using System.Collections.ObjectModel;
public ObservableCollections<Item> Items{get;set;}
...

然后改动类的代码,我这里只改动了IsChecked属性相关代码,其他属性类推:

// Item.cs
using System.ComponentModel;
using System.Runtime.CompilerServices;
public class Item : INotifyPropertyChanged
{
    private bool _IsChecked;
    public event PropertyChangedEventHandler PropertyChanged;
    private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
    {
      if (PropertyChanged != null)
      {
        PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
      }
    }
    public bool IsChecked
    {
      get
      {
        return _IsChecked;
      }
      set
      {
        if (_IsChecked != value)
        {
          _IsChecked = value;
          NotifyPropertyChanged();
        }
      }
    }
  }
}

然后在Xaml里对PropertyChanged进行监听(同样地可以扩展到其他属性的binding上面)

<!-- Main.xaml -->
<CheckBox IsChecked="{Binding IsChecked, UpdateSourceTrigger=PropertyChanged}"/>

这样完成以后,所有ObservableCollection中元素只要有一个属性有改变对应的显示便也都会改变。
binding还有不同模式。不同模式的用处详见这个链接

相关文章

网友评论

      本文标题:c#笔记之3(WPF Databinding Part 2)

      本文链接:https://www.haomeiwen.com/subject/cjqlbxtx.html