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 a CollectionViewSource
. 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 ordinary ObservableCollection<T>
and wrap the CollectionViewSource
around the ObservableCollection
:
// Gets or sets the CollectionViewSource
public CollectionViewSource ViewSource { get; set; }
// Gets or sets the ObservableCollection
public ObservableCollection<T> Collection { get; set; }
// Instantiates the objets.
public ViewModel () {
this.Collection = new ObservableCollection<T>();
this.ViewSource = new CollectionViewSource();
ViewSource.Source = this.Collection;
}
Then in the View part of the application you have nothing else to do as to bind the ItemsSource
of the CollectionControl
to the View property of the CollectionViewSource
instead of directly to the ObservableCollection
:
<DataGrid ItemsSource="{Binding ViewSource.View}" />
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:
// Specify a sorting criteria for a particular column
ViewSource.SortDescriptions.Add(new SortDescription ("columnName", ListSortDirection.Ascending));
// Let the UI control refresh in order for changes to take place.
ViewSource.View.Refresh();
You see, very very simple and intuitive. Hope that this helps other people like it helped me.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…