Search code examples
wpfxamldatagridprism

How to bind DataGrid Sorting event to Prism ViewModel DelegateCommand


How do I bind the sorting command of my datagrid to view model?

Below is my XAML Code

<DataGrid ItemsSource="{Binding ViewModels}"
          CanUserSortColumns="True"
          Sorting="{Binding ViewModel_SortingCommand}">
</DataGrid>

Below is the ViewModel implemented that cause the error in binding

ViewModel_SortingCommand = new DelegateCommand<DataGridSortingEventArgs>(ViewModel_Sorting;

public void ViewModel_Sorting(DataGridSortingEventArgs args)
{
    // Error on binding
}

Solution

  • Since Sorting is an event, you cannot bind it directly, but you can use an EventTrigger.

    <DataGrid ItemsSource="{Binding ViewModels}"
              CanUserSortColumns="True">
       <i:Interaction.Triggers>
          <i:EventTrigger EventName="Sorting">
             <i:InvokeCommandAction Command="{Binding ViewModel_SortingCommand}"/>
          </i:EventTrigger>
       </i:Interaction.Triggers>
    </DataGrid>
    

    If you use the legacy blend behaviors shipped with Blend, use this namespace:

    xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
    

    If you use the new Microsoft.Xaml.Behaviors.Wpf Nuget package, use this namespace:

    xmlns:i="http://schemas.microsoft.com/xaml/behaviors"
    

    If you need to process the event args in your command, set PassEventArgsToCommand to True:

    <b:InvokeCommandAction Command="{Binding FavContextMenuEditCmd}" PassEventArgsToCommand="True"/>
    

    Also note, that there is an EventArgsParameterPath property to specify a property in the event args that should be passed to the command and an EventArgsConverter property to use a converter. These are useful to avoid passing UI related types like event args to your view model.