Is there a way to bind an ItemsControl
(like ListView
开发者_如何学Python 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,
BenYou'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));
try to define this two attributes on the bining: IsSynchronizedWithCurrentItem=true BindsDirectlyToSource=true
i did not tried this but it might work..
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.
精彩评论