c# - 如何停止在 wpf 数据网格上拖动选择

标签 c# wpf xaml datagrid drag

嗨,这一切听起来可能微不足道,但我想停止在 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/

相关文章:

c# - 使用 XPATH 或 CSS 选择器在 Selenium 中查找元素

C# WPF Windows 10 (1803) TouchKeyboard 不可靠问题 (Prism ClickOnce)

c# - 图像缩放后我如何更新滚动查看器?

c# - 使用箭头在 DataGrid WPF 中导航文本框

c# - 如何使用 OnPlatform Xamarin 更改 BackgroundColor

c# - 相对源绑定(bind) Xamarin

c# - UWP: MapControl 透明背景

c# - 最好使用 int.Parse 或 Convert.ToInt32

c# - 在 HPUX 上运行 C#

c# - 在 Compact Framework 中将字节数组转换为结构