CollectionViewSource Filter not refreshed when Source is changed

前端 未结 3 1506
孤独总比滥情好
孤独总比滥情好 2020-12-30 06:55

I have a WPF ListView bound to a CollectionViewSource. The source of that is bound to a property, which can change if the user selects an option.

When the list view

3条回答
  •  梦谈多话
    2020-12-30 07:46

    I found a specific solution for extending the ObservableCollection class to one that monitors changes in the properties of the objects it contains here.

    Here's that code with a few modifications by me:

    namespace Solution
    {
    public class ObservableCollectionEx : ObservableCollection where T : INotifyPropertyChanged
        {
            protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
            {
                if (e != null)  // There's been an addition or removal of items from the Collection
                {
                    Unsubscribe(e.OldItems);
                    Subscribe(e.NewItems);
                    base.OnCollectionChanged(e);
                }
                else
                {
                    // Just a property has changed, so reset the Collection.
                    base.OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
    
                }
    
            }
    
            protected override void ClearItems()
            {
                foreach (T element in this)
                    element.PropertyChanged -= ContainedElementChanged;
    
                base.ClearItems();
            }
    
            private void Subscribe(IList iList)
            {
                if (iList != null)
                {
                    foreach (T element in iList)
                        element.PropertyChanged += ContainedElementChanged;
                }
            }
    
            private void Unsubscribe(IList iList)
            {
                if (iList != null)
                {
                    foreach (T element in iList)
                        element.PropertyChanged -= ContainedElementChanged;
                }
            }
    
            private void ContainedElementChanged(object sender, PropertyChangedEventArgs e)
            {
                OnPropertyChanged(e);
                // Tell the Collection that the property has changed
                this.OnCollectionChanged(null);
    
            }
        }
    }
    

提交回复
热议问题