I have 3 datagrid columns which are bound to different converters, which convert object fields to a string.
Now using a CollectionView for sorting how can I make the columns which use a converter sortable?
I use Entity Framework Database First, so I think I can not add a DependencyProperty to the object which fields are shown in the datagrid. Also adding more fields to the object in the database is no option.
Is there an elegant solution for this?
XAML sample code:
<DataGridTextColumn Width="200" Header="Status" SortMemberPath="myPath">
<DataGridTextColumn.Binding>
<Binding Converter="{StaticResource fieldsToStringConverter}"/>
</DataGridTextColumn.Binding>
</DataGridTextColumn>
As for C# I have the CollectionView which handles filtering and sorting but sorting currently only for normal (non converter) columns:
ICollectionView datagridView = CollectionViewSource.GetDefaultView(myDataGrid.ItemsSource);
The solution I have chosen for me is:
I use the Sorting event of the DataGrid to check which column was sorted. If a column using a converter was clicked I save the current sort direction and reassign the DataGrid.Itemssource sorted by the converter which creates a new CollectionView. Then set the sort direction of the clicked column to the saved sort direction.
This also works nice if an element is added or removed from the database as I can just use the sorting event function as a refresh if the current sorting is on one of the columns using a converter. This involves some added code not in the example below for the sake of clarity.
XAML
<DataGrid x:Name="dataGrid" ... Sorting="dataGrid_Sorting">
...
<DataGridTextColumn Width="200" Header="Status" SortMemberPath="mySortMemberPath">
<DataGridTextColumn.Binding>
<Binding Converter="{StaticResource myConverter}"/>
</DataGridTextColumn.Binding>
</DataGridTextColumn>
C#
private void dataGrid_Sorting(object sender, DataGridSortingEventArgs e)
{
string sortMemberPath = e.Column.SortMemberPath;
if (sortMemberPath == null || sortMemberPath == "")
{
return;
}
IValueConverter converter = null;
switch (sortMemberPath)
{
case "mySortMemberPath":
converter = new myConverter();
break;
}
if (converter != null)
{
e.Handled = true;
ListSortDirection direction = (e.Column.SortDirection != ListSortDirection.Ascending) ? ListSortDirection.Ascending : ListSortDirection.Descending;
if (direction == ListSortDirection.Ascending)
{
dataGrid.ItemsSource = --sort my list with converter--
}
else
{
dataGrid.ItemsSource = --sort my list with converter--
}
datagridView = CollectionViewSource.GetDefaultView(dataGrid.ItemsSource);
e.Column.SortDirection = direction;
applyCollectionViewFilter();
}
}