I want to bind a sort command to a DataGridColumn.Header the functions works if it's bind to a button, but I want to implement it anyway in the columns header of the datagrid. I use MVVMCross as pattern so I should use a IMVXCommand to fire the function.
This is my XAML code in WPF if the "SortColumn"-button gets clicked nothing happens.
<DataGridTemplateColumn Width="300" >
<DataGridTemplateColumn.Header>
<Button Content="SortColumn" Command="{Binding IMvxSortCommand}"/>
</DataGridTemplateColumn.Header>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding Names}"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
Thanks.
Read several discussions on Stackoverflow and tried different approaches.
Normally, sorting in the UI is a simple sorting of the data presentation layer and not the original data. For this reason, the sorting must take place in the view (and not in the view model or model).
You can move the sorting algorithm to a custom
IComparer<T>implementation or use the property basedICollectionView.SortDescriptionsfeature.Even if you don't use MVVM, implementing the sort algorithm in a dedicated
IComparer<T>implementation provides a very clean solution that doesn't pollute your data models with data view (UI) related sorting logic.If you use MVVM this separation becomes mandatory.
This solution is also cleaner in terms of the UI click area of the column headers as it will preserve its default click behavior. Because adding a
Buttonas content of the column header won't disable the default click behavior which will cause weird behavior if the user clicks on the padded area around theButton!NameComparer.cs
MainWindow.xaml.cs
MainWindow.xaml
If for whatever reason you insist on adding a
Buttonto attach anICommandthen you should define aDataTemplatefor theDataGridColumn.HeaderTemplateproperty. This way you can continue to use theDataGridColumn.Headerproperty independently: