WPF DataGrid: CommandBinding to a double click instead of using Events

前端 未结 4 1291
轮回少年
轮回少年 2021-02-01 02:37

I know how to use the MouseDoubleClick event with my DataGrid to grab the selectedvalue, but how would one go about using command bindings instead? That way my ViewModel can han

4条回答
  •  终归单人心
    2021-02-01 03:26

    Or, you could create a derived class

    public class CustomDataGrid : DataGrid
    {
        public ICommand DoubleClickCommand
        {
            get { return (ICommand)GetValue(DoubleClickCommandProperty); }
            set { SetValue(DoubleClickCommandProperty, value); }
        }
    
        // Using a DependencyProperty as the backing store for DoubleClickCommand.  This    enables animation, styling, binding, etc...
        public static readonly DependencyProperty DoubleClickCommandProperty =
            DependencyProperty.Register("DoubleClickCommand", typeof(ICommand), typeof(CustomDataGrid), new UIPropertyMetadata());
    
        public CustomDataGrid()
            : base()
        {            
            this.PreviewMouseDoubleClick += new MouseButtonEventHandler(CustomDataGrid_PreviewMouseDoubleClick);
        }
    
    
        void CustomDataGrid_PreviewMouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            if (DoubleClickCommand != null)
            {
                DoubleClickCommand.Execute(null);
            }
        }
    
    
    }
    

    and in XAML simply bind to the newly created command

    
    

提交回复
热议问题