WPF: How do I hook into a ListView's ItemsSource CollectionChanged notification?

前端 未结 3 659
感动是毒
感动是毒 2021-01-18 06:29

I have a ListView that is databound to an ObservableCollection ...



        
3条回答
  •  深忆病人
    2021-01-18 06:50

    An ObservableCollection{T} exposes the INotifyCollectionChanged.CollectionChanged event. When binding to an ItemsSource the data binding engine handles the propogation of changes from the source to the items control, but if you need to perform additional processing you can attach a handler to the CollectionChanged event and use the NotifyCollectionChangedEventArgs it provides.

    Assuming you have a public property on your view model named MyList:

    public ObservableCollection MyList
    {
      get
      {
        if(_viewModelMyList == null)
        {
          _viewModelMyList = new ObservableCollection;
          _viewModelMyList.CollectionChanged += (o, e) => 
          {
            // code to process change event can go here
            if(e.Action == NotifyCollectionChangedAction.Add)
            {
            }
          };
        }
        return _viewModelMyList;
      }
    }
    private ObservableCollection _viewModelMyList;
    

提交回复
热议问题