I have a Datagrid and don't like my workaround to fire a double click command on my viewmodel for the clicked (aka selected) row.
View:
<DataGrid EnableRowVirtualization="True"
ItemsSource="{Binding SearchItems}"
SelectedItem="{Binding SelectedItem}"
SelectionMode="Single"
SelectionUnit="FullRow">
<i:Interaction.Triggers>
<i:EventTrigger EventName="MouseDoubleClick">
<cmd:EventToCommand Command="{Binding MouseDoubleClickCommand}" PassEventArgsToCommand="True" />
</i:EventTrigger>
</i:Interaction.Triggers>
...
</DataGrid>
ViewModel:
public ICommand MouseDoubleClickCommand
{
get
{
if (mouseDoubleClickCommand == null)
{
mouseDoubleClickCommand = new RelayCommand<MouseButtonEventArgs>(
args =>
{
var sender = args.OriginalSource as DependencyObject;
if (sender == null)
{
return;
}
var ancestor = VisualTreeHelpers.FindAncestor<DataGridRow>(sender);
if (ancestor != null)
{
MessengerInstance.Send(new FindDetailsMessage(this, SelectedItem.Name, false));
}
}
);
}
return mouseDoubleClickCommand;
}
}
I want to get rid of the view related code (the one with the dependency object and the visual tree helper) in my view model, as this breaks testability somehow. But on the other hand this way I avoid that something happens when the user doesn't click on a row but on the header for example.
PS: I tried having a look at attached behaviors, but I cannot download from Skydrive at work, so a 'built in' solution would be best.
You may try this workaround:
In this case you have to specify
DataTemplate
for each column in theDataGrid
Way simpler than any of the proposed solutions here.
I'm using this one.
from WPF DataGrid: CommandBinding to a double click instead of using Events
Why don't you simply use the
CommandParameter
?Your command is something like this:
EDIT: I now use this instead of
Interaction.Triggers
:Here is how you could implement it using an attached behaviour:
EDIT: Now registers behaviour on
DataGridRow
rather thanDataGrid
so thatDataGridHeader
clicks are ignored.Behaviour:
Xaml:
You will then need to modify your
MouseDoubleClickCommand
to remove theMouseButtonEventArgs
parameter and replace it with yourSelectedItem
type.