Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom Sort in WPF DataGrid using MVVM

I have a datagrid that is bound to a collection of my ViewModel. One of its column has values that are very specific to business requirements. On this column it can contain an alphanumeric characters.

For example I can have column values A1,A20,AA,AA12,AAA. Now I want to custom sort this values, say I want the anything with most letters should go first or etchetera. There is a default sorting with DataGrid but only do normal sorting.

My question is how would you implement this through MVVM? We can get away with this through subscribing to an event in code behind and re arrange the whole collection. However this is not what I want, I am looking for suggestions or solutions on how to approach this.

I found this link Sorting on datagrid column with binded data and converter that is attaching a property for a DataGrid but what I want to do is to attach a property to be updated every time a user click on this column. Is it possible to attach a property in a DataGrid Column?

Possible duplicate of : Sorting on datagrid column with binded data and converter but this is not using MVVM.

like image 822
Jepoy_D_Learner Avatar asked Feb 17 '23 04:02

Jepoy_D_Learner


1 Answers

There are several strategies, but the most immediately accessible is to set up a DataGrid something like this...

<DataGrid ItemsSource="{Binding DriveList}" AutoGenerateColumns="False" >
    <DataGrid.Columns>
        <DataGridTextColumn Binding="{Binding Name}" SortMemberPath="DriveType"/>
    </DataGrid.Columns>
</DataGrid>

This example shows the grid binding to a list of drives on the host machine. The first column shows the information is bound to the property 'Name'. BUT when you click the column header, it will sort on a property which is not displayed, 'DriveType'. Strange example, but it works fine.

So in your app, you would amend your collection items to include a property that is not displayed, and populate it with values according to what you want. In the example in your question, you might use something like...

MySortString = MyName.ToString().Length;

And that will cause the sort to do what you are looking for, i.e., the longest value of 'MyName' will be first with shorter values after that. You have to repopulate 'MySortString' property every time you change sort methods or reload your data source.

This strategy is MVVM compliant because all you are doing in the VM is populating an additional property. Plus you can unit test it immediatly with Nunit or whatever.

like image 84
Gayot Fow Avatar answered Feb 27 '23 04:02

Gayot Fow