Bind DoubleClick Command from DataGrid Row to VM

后端 未结 4 813
悲&欢浪女
悲&欢浪女 2020-12-25 13:37

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:

   

        
4条回答
  •  梦毁少年i
    2020-12-25 14:00

    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.

提交回复
热议问题