Ik gebruikte de geïnteresseerde DataGrid van kat om een gedrag voor de wpf DataGrid te creëren.
The behavior saves the initial SortDescriptions and applies them on every change of ItemsSource
.
You can also provide a IEnumerable
which will cause a resort on every change.
Gedrag
public class DataGridSortBehavior : Behavior
{
public static readonly DependencyProperty SortDescriptionsProperty = DependencyProperty.Register(
"SortDescriptions",
typeof (IEnumerable),
typeof (DataGridSortBehavior),
new FrameworkPropertyMetadata(null, SortDescriptionsPropertyChanged));
///
/// Storage for initial SortDescriptions
///
private IEnumerable _internalSortDescriptions;
///
/// Property for providing a Binding to Custom SortDescriptions
///
public IEnumerable SortDescriptions
{
get { return (IEnumerable) GetValue(SortDescriptionsProperty); }
set { SetValue(SortDescriptionsProperty, value); }
}
protected override void OnAttached()
{
var dpd = DependencyPropertyDescriptor.FromProperty(ItemsControl.ItemsSourceProperty, typeof (DataGrid));
if (dpd != null)
{
dpd.AddValueChanged(AssociatedObject, OnItemsSourceChanged);
}
}
protected override void OnDetaching()
{
var dpd = DependencyPropertyDescriptor.FromProperty(ItemsControl.ItemsSourceProperty, typeof (DataGrid));
if (dpd != null)
{
dpd.RemoveValueChanged(AssociatedObject, OnItemsSourceChanged);
}
}
private static void SortDescriptionsPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
if (d is DataGridSortBehavior)
{
((DataGridSortBehavior) d).OnItemsSourceChanged(d, EventArgs.Empty);
}
}
public void OnItemsSourceChanged(object sender, EventArgs eventArgs)
{
//save description only on first call, SortDescriptions are always empty after ItemsSourceChanged
if (_internalSortDescriptions == null)
{
//save initial sort descriptions
var cv = (AssociatedObject.ItemsSource as ICollectionView);
if (cv != null)
{
_internalSortDescriptions = cv.SortDescriptions.ToList();
}
}
else
{
//do not resort first time - DataGrid works as expected this time
var sort = SortDescriptions ?? _internalSortDescriptions;
if (sort != null)
{
sort = sort.ToList();
var collectionView = AssociatedObject.ItemsSource as ICollectionView;
if (collectionView != null)
{
using (collectionView.DeferRefresh())
{
collectionView.SortDescriptions.Clear();
foreach (var sorter in sort)
{
collectionView.SortDescriptions.Add(sorter);
}
}
}
}
}
}
}
XAML met optionele SortDescriptions-parameter
ViewModel ICollectionView Setup
View = CollectionViewSource.GetDefaultView(_collection);
View.SortDescriptions.Add(new SortDescription("Sequence", ListSortDirection.Ascending));
Optioneel: ViewModel-eigenschap voor het verstrekken van veranderbare Sorteerbeschrijvingen
public IEnumerable SortDescriptions
{
get
{
return new List {new SortDescription("Sequence", ListSortDirection.Ascending)};
}
}