我想通过以下方式修改DataGrid的选择行为。通常情况下,当您选择多行时,然后单击已选中的某个项目,选择将重置为仅点击项目。我想对其进行更改,以便在没有任何键盘修改器的情况下单击其中一个多选行时,选择内容不会被修改。这样做的目标是允许多项目拖放。如何覆盖DataGrid选择行为?
我注意到,当上述默认行为被激活时,调用堆栈包括:
at System.Windows.Controls.DataGrid.OnSelectionChanged(SelectionChangedEventArgs e)
at System.Windows.Controls.Primitives.Selector.SelectionChanger.End()
at System.Windows.Controls.DataGrid.MakeFullRowSelection(ItemInfo info, Boolean allowsExtendSelect, Boolean allowsMinimalSelect)
at System.Windows.Controls.DataGrid.HandleSelectionForCellInput(DataGridCell cell, Boolean startDragging, Boolean allowsExtendSelect, Boolean allowsMinimalSelect)
at System.Windows.Controls.DataGridCell.OnAnyMouseLeftButtonDown(MouseButtonEventArgs e)
at System.Windows.RoutedEventArgs.InvokeHandler(Delegate handler, Object target)
at System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs)
at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised)
at System.Windows.UIElement.ReRaiseEventAs(DependencyObject sender, RoutedEventArgs args, RoutedEvent newEvent)
at System.Windows.UIElement.OnMouseDownThunk(Object sender, MouseButtonEventArgs e)
at System.Windows.RoutedEventArgs.InvokeHandler(Delegate handler, Object target)
因此它看起来像我应该能够通过重写DataGridCell.OnMouseLeftButtonDown,像这样修改的行为:
class MultiDragDataGridCell : DataGridCell
{
protected override void OnMouseLeftButtonDown(MouseButtonEventArgs e)
{
// This allows users to click-and-drag a multi-selection by handling the event before
// the default behavior (deselecting everything but the clicked cell) kicks in.
if (IsSelected && Keyboard.Modifiers == ModifierKeys.None)
{
e.Handled = true;
}
base.OnMouseLeftButtonDown(e);
}
}
但是,我无法让DataGrid创建MultiDragDataGridCell而不是普通的DataGridCell,因为实例化DataGridCell的类是内部的。任何人都知道我可以如何实现这一点,或者如果有另一种实现我想要的行为的方式?
其他的事情我想:
- 样式化DataGridCell的处理程序添加到的MouseLeftButtonDown。这不起作用,因为它在选择已经改变之后执行。
- 设计DataGridCell以向PreviewMouseLeftButtonDown添加处理程序。这有效,但它阻止我点击单元格内的任何按钮等。
我尝试了这一点,它的工作原理,但由于某些原因,它打乱了小区选择的显示。显示器似乎仍然遵循旧的行为,但实际SelectedItems是你所期望的。 – hypehuman