Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort WPF datagrid on data coming from a converter?

Tags:

.net

wpf

Question: How do I sort a datagrid on a column whose data comes from a converter?

I have a View Model that resembles:

public class MyViewModel
{
    public string Name { get; set; }
    public IEnumerable<string> Aliases { get; set; }
}

Further, I have a custom converter that maps the IEnumerable<string> to just a string.

My DataGrid resembles:

<DataGrid ItemsSource="...">
    <DataGrid.Columns>
        <DataGridTextColumn Width="10" Header="..." Binding="{Binding Path=Name}" />
        <DataGridTextColumn Width="10" Header="..." Binding="{Binding Path=Aliases, Converter={StaticResource myConverter}}" />
     ...

So far, so good. It displays as expected. The problem comes with the sorting.

When sorting by the Name, everything is fine. When sorting by the column whose data comes from the converter, I get a .NET exception:

The SortDescriptions added are not valid. The probable solutions are to set the CanUserSort on the Column to false, or to use SortMemberPath property on the Column, or to handle the Sorting event on DataGrid.

There's a solution floating around that suggests modifying the View Model to have a property that is similar to:

public class AliasesMapping
{
    public IEnumerable<string> Raw { get; set; }
    public string Converted { get; set; }
}

But... I'm wondering if there is a better or more standard approach to solving this. It feels like in this solution, a UI limitation is bleeding into the View Model layer.

UPDATE: here's the converter

[ValueConversion(typeof(IEnumerable<string>), typeof(string))]
public class AliasFormatConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        string converted = string.Empty;
        var val = value as IEnumerable<string>;

        if (val != null)
        {
            var list = new List<string>(val);
            list.Sort();

            converted = string.Join(",", list);
        }

        return converted;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}
like image 502
jglouie Avatar asked Sep 03 '25 02:09

jglouie


1 Answers

This is not tested but cannot format a comment

SortMemberPath="FirstString"

Public string FirtString { get { return Aliases[0]; } }

Not a whole lot different than the public string Converted { get; set; } that you want to get away from so probably not a lot of value to you. I was just saying that is what I would try.

like image 173
paparazzo Avatar answered Sep 06 '25 02:09

paparazzo