I resolved this issue myself :)
I created new behavior for grid with attached property UseBindingToSort. When I set this property to true then event Sorting on grid is subscribed. After grid fires event sorting I use custom comparer with IValueConverter which is defined in binding.
Solution is below:
Change on view
<DataGrid ItemsSource="{Binding People}" AutoGenerateColumns="False" my:GridSortingBehavior.UseBindingToSort="True">
New behavior with attached property:
public static class GridSortingBehavior
{
public static readonly DependencyProperty UseBindingToSortProperty = DependencyProperty.RegisterAttached("UseBindingToSort", typeof(bool), typeof(GridSortingBehavior), new PropertyMetadata(new PropertyChangedCallback(GridSortPropertyChanged)));
public static void SetUseBindingToSort(DependencyObject element, bool value)
{
element.SetValue(UseBindingToSortProperty, value);
}
private static void GridSortPropertyChanged(DependencyObject elem, DependencyPropertyChangedEventArgs e)
{
DataGrid grid = elem as DataGrid;
if (grid != null){
if ((bool)e.NewValue)
{
grid.Sorting += new DataGridSortingEventHandler(grid_Sorting);
}
else
{
grid.Sorting -= new DataGridSortingEventHandler(grid_Sorting);
}
}
}
static void grid_Sorting(object sender, DataGridSortingEventArgs e)
{
DataGridTextColumn clm = e.Column as DataGridTextColumn;
if (clm != null)
{
DataGrid grid = ((DataGrid)sender);
IValueConverter converter = null;
if (clm.Binding != null)
{
Binding binding = clm.Binding as Binding;
if (binding.Converter != null)
{
converter = binding.Converter;
}
}
if (converter != null)
{
e.Handled = true;
ListSortDirection direction = (clm.SortDirection != ListSortDirection.Ascending) ? ListSortDirection.Ascending : ListSortDirection.Descending;
clm.SortDirection = direction;
ListCollectionView lcv = (ListCollectionView)CollectionViewSource.GetDefaultView(grid.ItemsSource);
lcv.CustomSort = new ComparerWithComparer(converter, direction);
}
}
}
And finally my custom comparer:
class ComparerWithComparer : IComparer
{
private System.Windows.Data.IValueConverter converter;
private System.ComponentModel.ListSortDirection direction;
public ComparerWithComparer(System.Windows.Data.IValueConverter converter, System.ComponentModel.ListSortDirection direction)
{
this.converter = converter;
this.direction = direction;
}
public int Compare(object x, object y)
{
object transx = this.converter.Convert(x, typeof(string), null, System.Threading.Thread.CurrentThread.CurrentCulture);
object transy = this.converter.Convert(y, typeof(string), null, System.Threading.Thread.CurrentThread.CurrentCulture);
if (direction== System.ComponentModel.ListSortDirection.Ascending){
return Comparer.Default.Compare(transx, transy);
}
else
{
return Comparer.Default.Compare(transx, transy) * (-1);
}
}
}
And that's all.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…