When the user does a column sort in my DataGrid
, I want all null or empty cells to be sorted to the bottom, rather than the top.
I wrote an IComparer<T>
that makes sure blanks are always sorted downward, but I can't figure out how to apply it to the columns of my DataGrid
. Note that the initial sort of the DataGrid
, which I'm doing with the LINQ OrderBy()
method, works great. The problem is that all subsequent sorts performed by the user sort the blanks to the top.
Comparer Code
public class BlankLastStringComparer : IComparer<string>
{
public int Compare(string x, string y)
{
if (string.IsNullOrEmpty(x) && !string.IsNullOrEmpty(y))
return 1;
else if (!string.IsNullOrEmpty(x) && string.IsNullOrEmpty(y))
return -1;
else
return string.Compare(x, y);
}
}
Questions
How do I get the DataGridColumn
to use my comparer? Or if this is not possible, can you offer a workaround? I'm hoping for an MVVM friendly solution if possible.
this is how i do it : I do derive from the grid to keep all of this inside the class, so i attach to event handlers internally
attach to the sorting event
implement the method (i do this in a derived class)
I have an MVVM solution for this problem which makes use of attached behaviours. If you prefer to use code-behind, @Aran's solution will do the trick too.
https://stackoverflow.com/a/18218963/2115261