× {{alert.msg}} Never ask again
Get notified about new tutorials RECEIVE NEW TUTORIALS

Custom Sort in WPF DataGrid using MVVM

Codementor User
Feb 05, 2015
<p>There are several strategies, but the most immediately accessible is to set up a DataGrid something like this...</p> <pre><code> &lt;DataGrid ItemsSource="{Binding DriveList}" AutoGenerateColumns="False" &gt; &lt;DataGrid.Columns&gt; &lt;DataGridTextColumn Binding="{Binding Name}" SortMemberPath="DriveType"/&gt; &lt;/DataGrid.Columns&gt; &lt;/DataGrid&gt; </code></pre> <p>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'. <em>BUT</em> when you click the column header, it will sort on a property which is not displayed, 'DriveType'. Strange example, but it works fine.</p> <p>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...</p> <pre><code>MySortString = MyName.ToString().Length; </code></pre> <p>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.</p> <p>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.</p> <p>This tip was originally posted on <a href="http://stackoverflow.com/questions/17206421/Custom%20Sort%20in%20WPF%20DataGrid%20using%20MVVM/17225349">Stack Overflow</a>.</p>
comments powered by Disqus