Articles

Wpf DataGrid double click (AttachedProperty)

I needed to access the DoubleClick event of the WPF DataGrid in MVVM. After some searching on the Internet on how to accomplish this I found this solution which works very well.

Add this class to your solution:

  public static class AttachedCommands
  {
    public static readonly DependencyProperty DataGridDoubleClickProperty =
   DependencyProperty.RegisterAttached("DataGridDoubleClickCommand", typeof(ICommand), typeof(AttachedCommands), new PropertyMetadata(new PropertyChangedCallback(AttachOrRemoveDataGridDoubleClickEvent)));

    public static ICommand GetDataGridDoubleClickCommand(DependencyObject obj)
    {
      return (ICommand)obj.GetValue(DataGridDoubleClickProperty);
    }

    public static void SetDataGridDoubleClickCommand(DependencyObject obj, ICommand value)
    {
      obj.SetValue(DataGridDoubleClickProperty, value);
    }

    public static void AttachOrRemoveDataGridDoubleClickEvent(DependencyObject obj, DependencyPropertyChangedEventArgs args)
    {
      DataGrid dataGrid = obj as DataGrid;
      if (dataGrid != null)
      {
        ICommand cmd = (ICommand)args.NewValue;

        if (args.OldValue == null && args.NewValue != null)
          dataGrid.MouseDoubleClick += ExecuteDataGridDoubleClick;
        else if (args.OldValue != null && args.NewValue == null)
          dataGrid.MouseDoubleClick -= ExecuteDataGridDoubleClick;
      }
    }

    private static void ExecuteDataGridDoubleClick(object sender, MouseButtonEventArgs args)
    {
      DependencyObject obj = sender as DependencyObject;
      ICommand cmd = (ICommand)obj.GetValue(DataGridDoubleClickProperty);
      if (cmd != null)
      {
        if (cmd.CanExecute(obj))
          cmd.Execute(obj);
      }
    }
  }

In the XAML of the DataGrid add this line:

<DataGrid AutoGenerateColumns="false"
		x:Name="dataGridMembers"
		ItemsSource="{Binding Members, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
		SelectedItem="{Binding SelectedItem, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
	        SelectionMode="Single"
		SelectionUnit="FullRow"
		IsReadOnly="True"
		VerticalAlignment="Top"
		GridLinesVisibility="None"
	        AlternationCount="2"
		AlternatingRowBackground="#FFE9E9F2"
		ctrl:AttachedCommands.DataGridDoubleClickCommand="{Binding DataGridDoubleClickCommand}">

The 'DataGridDoubleClickCommand' is an ICommand property in your ViewModel. There is nothing more to it.

It's possible to extend this class, that way you can add Attached Commands to other events for controls.

Original article found here.