WPF Datagrid Multiple Selection without CTRL or Space

前端 未结 4 1792
遥遥无期
遥遥无期 2021-01-05 02:20

The WPF Datagrid has two selection modes, Single or Extended. The WPF ListView has a third - Multiple. This mode allows you to click and select multiple rows without CTRL or

4条回答
  •  难免孤独
    2021-01-05 02:55

    You can try this simple workaround without having to modifying/inheriting DataGrid control by handling preview mouse down event as follows:

    TheDataGrid.PreviewMouseLeftButtonDown += 
                     new MouseButtonEventHandler(TheDataGrid_PreviewMouseLeftButtonDown);
    
    
    void TheDataGrid_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
    {
        // get the DataGridRow at the clicked point
        var o = TryFindFromPoint(TheDataGrid, e.GetPosition(TheDataGrid));
        // only handle this when Ctrl or Shift not pressed 
        ModifierKeys mods = Keyboard.PrimaryDevice.Modifiers;
        if (o != null && ((int)(mods & ModifierKeys.Control) == 0 &&
                                                    (int)(mods & ModifierKeys.Shift) == 0))
        {
            o.IsSelected = !o.IsSelected;
            e.Handled = true;
        }
    }
    
    public static T TryFindFromPoint(UIElement reference, Point point)
                    where T:DependencyObject
    {
        DependencyObject element = reference.InputHitTest(point) as DependencyObject;
        if (element == null) 
            return null;
        else if (element is T) 
            return (T)element;
        else return TryFindParent(element);
    }
    

    The TryFindFromPoint method, from a blog post by Philipp Sumi, is used to get the DataGridRow instance from point you clicked.

    By checking ModifierKeys, you can still keep Ctrl and Shift as default behavior.

    Only one draw back from this method is that you can't click and drag to perform range select like it can originally.

提交回复
热议问题