I am looking for a way to re-sort my DataGrid
when the underlying data has changed.
(The setting is quite standard: The DataGrid's ItemSource
property is bound to an ObservableCollection
; The columns are DataGridTextColumns
; The data inside the DataGrid reacts correctly on changes inside the ObservableCollection; Sorting works fine when clicked with the mouse)
Any ideas ?
For anyone else having this problem, this may get you started... If you have a collection of INotifyPropertyChanged items, you can use this instead of ObservableCollection - it will refresh when individual items in the collection change: note: since this flags the items as removed then readded (even though they aren't actually removed and added,) selections may get out of sync. It's good enough for my small personal projects, but it's not ready to release to customers...
It took me the whole afternoon but I finally found a solution that is surprisingly simple, short and efficient:
To control the behaviors of the UI control in question (here a
DataGrid
) one might simply use aCollectionViewSource
. It acts as a kind of representative for the UI control inside your ViewModel without completely breaking the MVMM pattern.In the ViewModel declare both a
CollectionViewSource
and an ordinaryObservableCollection<T>
and wrap theCollectionViewSource
around theObservableCollection
:Then in the View part of the application you have nothing else to do as to bind the
ItemsSource
of theCollectionControl
to the View property of theCollectionViewSource
instead of directly to theObservableCollection
:From this point on you can use the
CollectionViewSource
object in your ViewModel to directly manipulate the UI control in the View.Sorting for example - as has been my primary problem - would look like this:
You see, very very simple and intuitive. Hope that this helps other people like it helped me.
This is more for clarification than it is an answer, but WPF always binds to an
ICollectionView
and not the source collection.CollectionViewSource
is just a mechanism used to create/retrieve the collection view.Here's a great resource about the topic which should help you make better use of collection views in WPF: http://bea.stollnitz.com/blog/?p=387
Using
CollectionViewSource
in XAML can actually simplify your code some:Some people argue that when following the MVVM pattern, the view model should always expose the collection view but in my opinion, it just depends on the use case. If the view model is never going to directly interact with the collection view, it's just easier to configure it in XAML.
Use LiveSorting . Example from wpf.2000things.com.
I cannot see any obviously easy ways, so I would try an Attached Behavior. It is a bit of a bastardization, but will give you what you want:
Then, you can attach it via:
The answer by sellmeadog is either overly complicated or out of date. It's super simple. All you have to do is: