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 ?
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.
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:
<Window.Resources>
<CollectionViewSource Source="{Binding MySourceCollection}" x:Key="cvs">
<CollectionViewSource.SortDescriptions>
<scm:SortDescription PropertyName="ColumnName" />
</CollectionViewSource.SortDescriptions>
</CollectionViewSource>
</Window.Resources>
...
<DataGrid ItemsSource="{Binding Source={StaticResource cvs}}">
</DataGrid>
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.
The answer by sellmeadog is either overly complicated or out of date. It's super simple. All you have to do is:
<UserControl.Resources>
<CollectionViewSource
Source="{Binding MyCollection}"
IsLiveSortingRequested="True"
x:Key="MyKey" />
</UserControl.Resources>
<DataGrid ItemsSource="{Binding Source={StaticResource MyKey} }" >...
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:
public static class DataGridAttachedProperty
{
public static DataGrid _storedDataGrid;
public static Boolean GetResortOnCollectionChanged(DataGrid dataGrid)
{
return (Boolean)dataGrid.GetValue(ResortOnCollectionChangedProperty);
}
public static void SetResortOnCollectionChanged(DataGrid dataGrid, Boolean value)
{
dataGrid.SetValue(ResortOnCollectionChangedProperty, value);
}
/// <summary>
/// Exposes attached behavior that will trigger resort
/// </summary>
public static readonly DependencyProperty ResortOnCollectionChangedProperty =
DependencyProperty.RegisterAttached(
"ResortOnCollectionChangedProperty", typeof (Boolean),
typeof(DataGridAttachedProperty),
new UIPropertyMetadata(false, OnResortOnCollectionChangedChange));
private static void OnResortOnCollectionChangedChange
(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e)
{
_storedDataGrid = dependencyObject as DataGrid;
if (_storedDataGrid == null)
return;
if (e.NewValue is Boolean == false)
return;
var observableCollection = _storedDataGrid.ItemsSource as ObservableCollection;
if(observableCollection == null)
return;
if ((Boolean)e.NewValue)
observableCollection.CollectionChanged += OnCollectionChanged;
else
observableCollection.CollectionChanged -= OnCollectionChanged;
}
private static void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
{
if (e.OldItems == e.NewItems)
return;
_storedDataGrid.Items.Refresh()
}
}
Then, you can attach it via:
<DataGrid.Style>
<Style TargetType="DataGrid">
<Setter
Property="AttachedProperties:DataGridAttachedProperty.ResortOnCollectionChangedProperty"
Value="true"
/>
</Style>
</DataGrid.Style>
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...
public class ObservableCollection2<T> : ObservableCollection<T>
{
public ObservableCollection2()
{
this.CollectionChanged += ObservableCollection2_CollectionChanged;
}
void ObservableCollection2_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
if (e.OldItems != null)
foreach (object o in e.OldItems)
remove(o);
if (e.NewItems != null)
foreach (object o in e.NewItems)
add(o);
}
void add(object o)
{
INotifyPropertyChanged ipc = o as INotifyPropertyChanged;
if(ipc!=null)
ipc.PropertyChanged += Ipc_PropertyChanged;
}
void remove(object o)
{
INotifyPropertyChanged ipc = o as INotifyPropertyChanged;
if (ipc != null)
ipc.PropertyChanged -= Ipc_PropertyChanged;
}
void Ipc_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
NotifyCollectionChangedEventArgs f;
f = new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, sender);
base.OnCollectionChanged(f);
f = new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, sender);
base.OnCollectionChanged(f);
}
}
来源:https://stackoverflow.com/questions/11505283/re-sort-wpf-datagrid-after-bounded-data-has-changed