WPF DataGrid地图鼠标中键点击ctrl +左键单击

时间:2015-02-23 23:31:49

标签: c# wpf datagrid

我想实现一个功能,点击鼠标中键与使用ctrl +左键单击功能相同。

这将让用户只用鼠标中键选择多个单元格。

1 个答案:

答案 0 :(得分:0)

在您的标记中,将处理程序挂钩到PreviewMouseDown事件:

<DataGrid x:Name="MyDataGrid" PreviewMouseDown="MyDataGrid_PreviewMouseDown" SelectionMode="Extended" SelectionUnit="Cell"></DataGrid>

然后在您的代码中,您可以执行以下操作:

private void MyDataGrid_PreviewMouseDown(object sender, MouseButtonEventArgs e)
{
    if (e.ChangedButton == MouseButton.Middle && e.ButtonState == MouseButtonState.Pressed)
    {
        MyDataGrid.Focus();

        DependencyObject dep = (DependencyObject)e.OriginalSource;

        // Traverse the visual tree looking for DataGridCell
        while ((dep != null) && !(dep is DataGridCell))
            dep = VisualTreeHelper.GetParent(dep);

        if (dep == null)
        {
            // Didn't find DataGridCell
            return;
        }

        DataGridCell cell = dep as DataGridCell;

        if (cell != null)                
        {
            DataGridCellInfo cellInfo = new DataGridCellInfo(cell);
            if(!MyDataGrid.SelectedCells.Contains(cellInfo))
            {
                // The cell is not already selected, add it to the selection
                MyDataGrid.SelectedCells.Add(new DataGridCellInfo(cell));
            }
            else
            {
                // Cell is already part of selection, remove it (same behaviour as ctrl+left click)
                MyDataGrid.SelectedCells.Remove(cellInfo);
            }

        }
    } 
}