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:
Here is how you could implement it using an attached behaviour:
EDIT: Now registers behaviour on DataGridRow rather than DataGrid so that DataGridHeader clicks are ignored.
Behaviour:
public class Behaviours
{
public static DependencyProperty DoubleClickCommandProperty =
DependencyProperty.RegisterAttached("DoubleClickCommand", typeof(ICommand), typeof(Behaviours),
new PropertyMetadata(DoubleClick_PropertyChanged));
public static void SetDoubleClickCommand(UIElement element, ICommand value)
{
element.SetValue(DoubleClickCommandProperty, value);
}
public static ICommand GetDoubleClickCommand(UIElement element)
{
return (ICommand)element.GetValue(DoubleClickCommandProperty);
}
private static void DoubleClick_PropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var row = d as DataGridRow;
if (row == null) return;
if (e.NewValue != null)
{
row.AddHandler(DataGridRow.MouseDoubleClickEvent, new RoutedEventHandler(DataGrid_MouseDoubleClick));
}
else
{
row.RemoveHandler(DataGridRow.MouseDoubleClickEvent, new RoutedEventHandler(DataGrid_MouseDoubleClick));
}
}
private static void DataGrid_MouseDoubleClick(object sender, RoutedEventArgs e)
{
var row= sender as DataGridRow;
if (row!= null)
{
var cmd = GetDoubleClickCommand(row);
if (cmd.CanExecute(row.Item))
cmd.Execute(row.Item);
}
}
}
Xaml:
You will then need to modify your MouseDoubleClickCommand to remove the MouseButtonEventArgs parameter and replace it with your SelectedItem type.