天天看点

WPF ListView即时更新

原文:

WPF ListView即时更新

1、ListView 的 ItemSource 使用 BindingList < T >;

 注:由于 List < T > 没有实现 INotifyPropertyChanged 接口,

   因此若使用 List < T > 作为 ItemSource,则当 ListView 新增、删除 Item 时,ListView UI 会不能即时更新;

2、对应 ListView 的 Item 的类 T 实现 INotifyPropertyChanged 接口;

  T 中 UI 绑定对应的属性 Set 设值后,调用

PropertyChanged()

函数以通知 UI 该属性已改变,示例如下:

  public partial class MainWindow : Window

  {

    public MainWindow()

    {

      InitializeComponent();

      BindingList<Customer> listCustomer = new BindingList<Customer>();

      listCustomer.Add(new Customer() { Name = "ZhangSan" });

      listView.ItemsSource = listCustomer;

    }

  }

  public class Customer : INotifyPropertyChanged

    public string name;

    public string Name

      get { return name; }

      set { name = value; OnPropertyChanged(new PropertyChangedEventArgs("Name")); }

    #region // INotifyPropertyChanged成员

    public event PropertyChangedEventHandler PropertyChanged;

    public void OnPropertyChanged(PropertyChangedEventArgs e)

      if (PropertyChanged != null)

      {

        PropertyChanged(this, e);

      }

    #endregion