How to use WPF DataGridRow events with Interaction.Triggers / MVVM EventToCommand

Simon_Weaver picture Simon_Weaver · Jul 22, 2012 · Viewed 7.9k times · Source

The MVVMLight EventToCommand can be used to fire an ICommand on your viewmodel quite easily.

<DataGrid>
    <i:Interaction.Triggers>
        <i:EventTrigger EventName="SelectionChanged">
            <GalaSoft_MvvmLight_Command:EventToCommand
                Command="{Binding ProductSelectionChangedCommand, Mode=OneWay}    "
                CommandParameter="{Binding SelectedItems, ElementName=gridProducts}" />
        </i:EventTrigger>
    </i:Interaction.Triggers>
</DataGrid>

In this instance the SelectionChanged event belongs to DataGrid, and the Interaction.Triggers xaml is nested directly inside DataGrid.

I cannot figure out how to do the same when the event is a DataGridRow (which has its own events for each row).

I managed to do this, but it involves a handler function which I'd like to avoid :

<DataGrid>
    <DataGrid.ItemContainerStyle>
        <Style TargetType="DataGridRow">
            <EventSetter Event="DataGridRow.MouseEnter" 
                         Handler="Row_MouseEnter"/>
        </Style>
    </DataGrid.ItemContainerStyle>
</DataGrid>

In the Row_MouseEnter event (on my .xaml.cs file) I just 'find the command' on the ViewModel and trigger it programatically.

I'd really like to know if there's a way of doing the same directly with Interaction.Triggers

(FYI: What I'm doing is I have a panel above the grid which displays details of the row that the mouse is over before clicking on it - which triggers a detail view).

Answer

Rohit Vats picture Rohit Vats · Jul 22, 2012

Yeah you can directly bind to the command in your ViewModel by creating your own custom behaviour class and using it in xaml file. These links might get you started - Binding using interactivity and Binding through interaction in MVVM