Search code examples
wpfdatagridviewobservablecollectionicollectionview

How to refresh ICollectionView when new item added into it's internal ObservableCollection


Please see my code below

private ObservableCollection<Person> testList = new ObservableCollection<Person>();

    public ObservableCollection<Person> TestList
    {
        get { return testList; }
        set
        {
            if (testList != value)
            {
                testList = value;
                SetProperty<ObservableCollection<Person>>(ref testList, value);
            }
        }
    }

    private ListCollectionView personListView;

    public ICollectionView PersonListView
    {
        get
        {
            if (personListView == null)
            {
                personListView = new ListCollectionView(TestList)
                {
                    Filter = p => FilterPerson((Person)p)
                };
            }
            return personListView;
        }

    }

I want to know how to update PersonListView and refresh UI when new item is inserted into TestList, or the whole TestList is re-assigned? I've tried call Refresh method in TestList set method, but when a new item is inserted into the collection, set method will not be invoked.

Thanks


Solution

  • I think you can add a collection changed event to the TestList observable collection and filter the PersonListView in it.

         TestList.CollectionChanged += TestList_CollectionChanged;
    
         void TestList_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
                {
                    if (e.NewItems != null)
                    {
                        /// Filter the PersonListView
                    }
                }