Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have an ObservableCollection<T>. I've bound it to a ListBox control and I've added SortDescriptions 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
306 views
Welcome To Ask or Share your Answers For Others

1 Answer

Brute force:

  1. Attach handler to each PropertyChanged event for each child item
  2. Grab the ListCollectionView from your CollectionViewSource
  3. 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...