天天看點

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