嗨,这一切听起来可能微不足道,但我想停止在 WPF
DataGrid
上拖动选择
我有一个简单的网格,例如
<DataGrid ItemsSource="{Binding Items}" SelectionMode="Extended">
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding .}"/>
</DataGrid.Columns>
</DataGrid>
如何停止单击拖动时的多项选择,但通过 Shift 和 Ctrl 进行多项选择。
谢谢
最佳答案
Mikolaytis's answer是不完整的。使用该解决方案,只要按下鼠标按钮,单击未选定的行就会选择该行及其上方第一个选定行之间的所有行。这是 DataGrid._isDraggingSelection 仍然为 true 的副作用,在其他鼠标事件驱动的操作中对其进行评估。
Il Vic's answer虽然我没有尝试过,但它比必要的要复杂得多。
相反,在 DataGrid.OnMouseMove() 的重写中(如 Mikolaytis 的答案中所做的那样),通过反射调用私有(private)方法 DataGrid.EndDragging():
public class MyDataGrid : DataGrid
{
private static readonly FieldInfo s_isDraggingSelectionField =
typeof(DataGrid).GetField("_isDraggingSelection", BindingFlags.Instance | BindingFlags.NonPublic);
private static readonly MethodInfo s_endDraggingMethod =
typeof(DataGrid).GetMethod("EndDragging", BindingFlags.Instance | BindingFlags.NonPublic);
// DataGrid.OnMouseMove() serves no other purpose than to execute click-drag-selection.
// Bypass that, and stop 'is dragging selection' mode for DataGrid
protected override void OnMouseMove(MouseEventArgs e)
{
if ((bool)(s_isDraggingSelectionField?.GetValue(this) ?? false))
s_endDraggingMethod.Invoke(this, new object[0]);
}
}
简单来说,拖动选择开始后,下一个鼠标移动事件就会结束它。
关于c# - 如何停止在 wpf 数据网格上拖动选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38204291/