您可以尝试这个简单的解决方法,而无需通过处理预览鼠标按下事件来修改/继承 DataGrid 控件,如下所示:
TheDataGrid.PreviewMouseLeftButtonDown += new MouseButtonEventHandler(TheDataGrid_PreviewMouseLeftButtonDown);
void TheDataGrid_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
// get the DataGridRow at the clicked point
var o = TryFindFromPoint<DataGridRow>(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;
}
}
方法 TryFindFromPoint 是从该链接http://www.hardcodet.net/2008/02/find-wpf-parent借用的函数,以便从您单击的点获取 DataGridRow 实例
通过检查 ModifierKeys,您仍然可以将 Ctrl 和 Shift 保留为默认行为。
这种方法唯一的一个缺点是您不能像原来那样单击并拖动来执行范围选择。但值得一试。