c# - 如何在 wpf 中检测拖动开始

标签 c# wpf user-interface drag-and-drop

我从这个问题知道如何处理拖放

https://stackoverflow.com/a/17872857/982161

但我无法检测到拖动事件何时开始,因此我可以准备一些资源...

如果我打印这些事件,首先是 Drop,然后是 Drag..

如何干净利落地处理

我的代码很简单

    private void Label_MouseDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
    {
        var lbl = (Label)sender;
        DragDrop.DoDragDrop(lbl, lbl.Content, DragDropEffects.Move);
        Console.WriteLine("Drag...");
    }

    private void Label_Drop(object sender, DragEventArgs e)
    {
        Console.WriteLine("Drop...");
    }

    private void Label_DragEnter(object sender, DragEventArgs e)
    {
        Console.WriteLine("Label_DragEnter...");
    }

    private void Label_DragLeave(object sender, DragEventArgs e)
    {
        Console.WriteLine("Label_DragLeave...");
    }

最佳答案

长话短说:如果您想在放置标签之前准备好资源,请在调用 DragDrop 方法之前或在 OnPreviewMouseDown 事件中编写该代码。


长话短说:

使用 Snoop我能够查看拖动标签时触发的事件。

似乎唯一触发的事件是 PreviewMouseDownMouseDown

enter image description here

所以我们应该只实现那些事件。

private void Lbl_OnMouseDown(object sender, MouseButtonEventArgs e)
{
    var lbl = (Label)sender;
    DragDrop.DoDragDrop(lbl, lbl.Content, DragDropEffects.Move);
    Console.WriteLine("Drag...");
}

private void UIElement_OnPreviewMouseDown(object sender, MouseButtonEventArgs e)
{
    Console.WriteLine("Label_PreviewMouseDown...");
}

这将导致在开始拖动标签时首先打印“Label_PreviewMouseDown...”,在完成拖动标签时打印“Drag...”。

enter image description here

然而,这并不是全部事实。

让我们稍微修改一下代码。让我们添加 DateTime.Now.Second 来测试消息实际触发的时间。然后我将拖动标签几秒钟,然后放下它以查看打印到控制台的顺序。

private void Lbl_OnMouseDown(object sender, MouseButtonEventArgs e)
{
    var lbl = (Label)sender;

    Console.WriteLine("Label_OnMouseDown_BeforeDragging..." + DateTime.Now.Second);

    DragDrop.DoDragDrop(lbl, lbl.Content, DragDropEffects.Move);

    Console.WriteLine("Label_OnMouseDown_AfterDragging..." + DateTime.Now.Second);
}

private void UIElement_OnPreviewMouseDown(object sender, MouseButtonEventArgs e)
{
    Console.WriteLine("Label_PreviewMouseDown..." + DateTime.Now.Second);
}

现在让我们再次尝试拖动。

enter image description here

事实证明,OnMouseDown 发生在您完成拖动之前。 DoDragDrop 方法会在那里暂停代码,直到您放下标签,然后您才能继续并打印到控制台。

因此:如果您想在放置标签之前准备好资源,请在调用 DragDrop 方法之前或在 OnPreviewMouseDown 事件中编写该代码。

希望这对您有所帮助。

关于c# - 如何在 wpf 中检测拖动开始,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40089298/

相关文章:

C# 泛型方法值

c# - 集合类型名称中的 '1 是什么

c# - 如何将现代标签链接 float 到左侧?

wpf - 异步 MVVM 命令

php - 仅在元素未被拖动时获取输出

c# - 如何自动点击第 3 方 Java 小程序?

javascript - 如何使用子元素以外的元素作为拖动 handle ?

c# - 为什么 'unbox.any' 不像 'castclass' 那样提供有用的异常文本?

c# - 一次调用从 Redis 读取多个哈希值

c# - 以编程方式启动 Windows 10 表情符号热键