Konrad Viltersten
Konrad Viltersten

Reputation: 39058

Unable to sort by a column with multi-binding and converter

I've noticed that when my column is bound to a field in VM, everything works fine and I get the sorting working just as expected. However, due to a weird requirement from the customer, I needed to use multi-binding and a converter to return a different value when status of another column varies. So I ended up in something like this.

<DataGridTextColumn Header="Original">
  <DataGridTextColumn.Binding>
    <MultiBinding Converter="{StaticResource OriginalConverter}">
      <Binding Path="Status.Id" />
      <Binding Path="Original" />
      <Binding Path="Substitution" />
    </MultiBinding>
  </DataGridTextColumn.Binding>
  <DataGridTextColumn.ElementStyle>
    ...
  </DataGridTextColumn.ElementStyle>
</DataGridTextColumn>

I'm not sure how to make the column to be sorted. Turning off the converter is out of the question, as it's the one of the main features of the grid. I'm using collection view source in my data grid component, if it's of any relevance. The converter itself looks as follows.

public class OriginConverter : IMultiValueConverter
{
  public object Convert(Object[] values, Type type, object param, CultureInfo culture)
  {
    int status = (int) values[0];
    int original = ...;
    int substitution = ...;
    return status < 3 ? original : substitution;
  }
}

Or is sorting just not available when using converters? That sounds unlikely...

I've found this hint, which actually works a little bit, because the column gets the triangle that accompanies the sorted columns but the sort needs to be with respect to the shown value, i.e. the one that converter provides and in his example it's fixed to a one of the bound properties.

Upvotes: 1

Views: 1311

Answers (1)

daniel
daniel

Reputation: 1070

SortMemberPath can help you

<DataGridTextColumn Header="Original" SortMemberPath="SortParam">
  <DataGridTextColumn.Binding>
    <MultiBinding Converter="{StaticResource OriginalConverter}">
      <Binding Path="Status.Id" />
      <Binding Path="Original" />
      <Binding Path="Substitution" />
    </MultiBinding>
  </DataGridTextColumn.Binding>
  <DataGridTextColumn.ElementStyle>
    ...
  </DataGridTextColumn.ElementStyle>
</DataGridTextColumn>
public int SortParam
{
  get
  { 
    return (bool)(new OriginalConverter())
      .Convert(new object[] { Status.Id, Original, Substitution }, typeof(int), null, null); 
  }
}

Remark: SortMemberPath only work for property, so you better to have a computed property in your model, sad

In case the model is autogenerated (EF, nHybernate or another OCR mapper) or if the alterations to the model aren't allowed (lack to access to source code), the programmer can use a partial class to adhere the extra properties needed to the original model, without any need of inheritance nor modifications to the T4-file's transforms.

Upvotes: 2

Related Questions