We are building a WPF application containing a DataGrid, which should call a function on the currently selected row if that row is double-clicked. We are aiming for an MVVM approach where possible, trying to avoid events.
Because I've done something similar for a DataGrid in a previous application, I thought this would work:
<DataGrid.InputBindings>
<MouseBinding MouseAction="LeftDoubleClick" Command="{Binding ShowDetailsCommand}"/>
</DataGrid.InputBindings>
In this working application, ShowDetailsCommand
points to a method which accesses the currently selected DataGrid item via a data binding to SelectedItem
.
Trying this same approach in the new project does not seem to work at all. The method which the command points to is never called (tested with a breakpoint and console output), and there is also no error message about the command not being found in the DataContext. We have also tried to move the <InputBindings>
block directly into the Window object just to test if the DataContext may have changed further down, but double-clicking still produced no reaction.
As far as I can tell, the only major differences between the two DataGrids are:
ItemsSource
was manually bound to a collection of objects, while the new one's Binding was created by dragging a DataSet onto it in the designerDataContext="{Binding RelativeSource={RelativeSource Mode=Self}}"
, declared on the Window)Could either of these be the cause for an InputBinding not working? If not, is there anything else we could be doing wrong? Apologies if this is not enough information, I am just very unsure where the problem might be. I will try to supply more information about the code if needed.
Try to bind to the ShowDetailsCommand
of the DataContext
of the parent window using a RelativeSource
:
Command="{Binding DataContext.ShowDetailsCommand,
RelativeSource={RelativeSource AncestorType=Window}}"