views:

24

answers:

3

Hello,

Is there a way to bind an ItemsControl (like ListView or DataGrid) to a sorted collection such that:

  • whenever the collection is resorted via code, the ItemsControl automatically reflects the new sort order,
  • AND whenever the ItemsControl is sorted, it re-sorts the collection?

Thank you,
Ben

A: 

try to define this two attributes on the bining: IsSynchronizedWithCurrentItem=true BindsDirectlyToSource=true

i did not tried this but it might work..

Chen Kinnrot
A: 

Putting your items into an ObservableCollection and then binding to the ObservableCollection should do the trick. Any sorting done on the ObservableCollection should "translate" to the UI layer.

cozykozy
Something like this is what I was hoping for but it didn't seem to work.
Ben Gribaudo
A: 

You'll need to use the

CollectionViewSource.GetDefaultView() 

method to get the default view of your ObservableCollection and apply the sort on that.

For example, below I'm sorting the ObservableCollection named 'authors' by BookTitle.

        ObservableCollection<Author> authors = new ObservableCollection<Author>();
        authors = PopulateCollection();

        // Sort by BookTitle
        System.ComponentModel.ICollectionView colView;
        colView = CollectionViewSource.GetDefaultView(authors);
        colView.SortDescriptions.Add(new System.ComponentModel.SortDescription("BookTitle", ListSortDirection.Descending));
ChrisNel52