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

前端 未结 3 657
感动是毒
感动是毒 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<T> MyList
    {
      get
      {
        if(_viewModelMyList == null)
        {
          _viewModelMyList = new ObservableCollection<T>;
          _viewModelMyList.CollectionChanged += (o, e) => 
          {
            // code to process change event can go here
            if(e.Action == NotifyCollectionChangedAction.Add)
            {
            }
          };
        }
        return _viewModelMyList;
      }
    }
    private ObservableCollection<T> _viewModelMyList;
    
    0 讨论(0)
  • 2021-01-18 07:00

    you are going to have to attach the handler to your list. Or, use a CollectionView and hook the changed event there.

    in your codebehind, do like this:

    MyList.CollectionChanged += new NotifyCollectionChangedEventHandler( this.MyCollectionChanged );
    
    
    private void SortCollectionChanged( object sender, NotifyCollectionChangedEventArgs e )
    {
      Debug.WriteLine( "Changed" );
    }
    
    0 讨论(0)
  • 2021-01-18 07:06

    By default the ItemsSource is of type IEnumerable. You need to first cast to a type that has access to the CollectionChanged event, then add a handler for that event.

    ((INotifyCollectionChanged)List1.ItemsSource).CollectionChanged +=
        new NotifyCollectionChangedEventHandler(List1CollectionChanged);
    
    public void List1CollectionChanged(Object sender, NotifyCollectionChangedEventArgs e)
    {
        // Your logic here
    }
    


    Note: I cast it to INotifyCollectionChanged in my example, but you can really cast it to any object that implements that. Though, as a best practice, you should cast to the most generic type that gives you access to the methods/properties/events you need. So, while you can cast it to an ObservableCollection, you don't need to. INotifyCollectionChanged contains the event you need and if you ever decide to use some other type of collection that implements it, this will continue to work, whereas casting to an ObservableCollection means that if you one day decide that you're list is now of type MyOwnTypeOfObservableCollectionNotDerivedFromObservableCollection than this will break. ;)

    P.S. This should go in the xaml code-behind.

    0 讨论(0)
提交回复
热议问题