Observable Collection Property Changed on Item in the Collection
Brute force:
- Attach handler to each PropertyChanged event for each child item
- Grab the ListCollectionView from your CollectionViewSource
- Call Refresh.
EDIT:
The code for 1, 2 would live in your code-behind.
For #1, you'd do something like:
private void Source_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
switch (e.Action)
{
case NotifyCollectionChangedAction.Add:
foreach( SomeItem item in e.NewItems)
{
item.PropertyChanged += new PropertyChangedEventHandler(_SomeItem_PropertyChanged);
}
break;
....
**HANDLE OTHER CASES HERE**
....
}
}
For #2, in your CollectionChanged handler, you would do something like:
private void _SomeItem_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
ListCollectionView lcv = (ListCollectionView)(CollectionViewSource.GetDefaultView(theListBox.ItemsSource));
lcv.Refresh();
}
EDIT2: However, in this case, I would strongly suggest that you also check ListCollectionView.NeedsRefresh and only refresh if that is set. There's no reason to re-sort if your properties have changed which don't affect the sort.
Nate
Dad. Geek. Gamer. Web developer. Cloud user. Old Car enthusiast. Blogger.
Updated on July 17, 2022Comments
-
Nate almost 2 years
I have an
ObservableCollection<T>
. I've bound it to a ListBox control and I've addedSortDescriptions
to the Items collection on the ListBox to make the list sort how I want.I want to resort the list at ANY point when any property changed on a child element.
All my child elements implement
INotifyPropertyChanged
. -
Nate about 15 yearsWould this code live in my presentation tier? Window.Xaml.Cs? What would code for #1 and #2 look like?
-
Nate about 15 yearsThat is exactly what I needed. I ended up only using the second part, since in my case I have an event that is causing the change, so I only needed #2.
-
Odrade over 13 yearsObservableCollection<T> does not listen to the PropertyChanged events on its elements, so this will fail to re-sort when a property of one of the elements is changed. msdn.microsoft.com/en-us/magazine/dd252944.aspx