c# - WPF DragDropEffects 在 Drop 事件中未正确设置

标签 c# .net wpf

我正在尝试在我的应用程序中拖放一些数据。如果未按下控制键,我希望 DragDropEffects 为 Move;如果按下控制键,则为 Copy。看起来这应该是微不足道的,但我搜索了很多并没有找到答案。

这是我的代码,大致基于 Microsoft's example :

private static void dragSource_MouseMove(object sender, MouseEventArgs e)
{
    DragDrop.DoDragDrop(currentDragDef.DragSource, currentDragDef.Data, DragDropEffects.All);
    e.Handled = true;
}

private static void dropTarget_DragOver(object sender, DragEventArgs e)
{
    bool ctrlKey = Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.RightCtrl);
    if ((e.Effects & DragDropEffects.Move) == DragDropEffects.None || ctrlKey)
    {
        // Control key is pressed or move is not allowed. Do copy/link.
        e.Effects &= ~DragDropEffects.Move;
    }
    else
    {
        // Control key not pressed. Do move.
        e.Effects &= (DragDropEffects.Move | DragDropEffects.Scroll);
    }
    e.Handled = true;
}

e.EffectsdropTarget_DragOver 中设置得很好。每当我按下 Control 时,鼠标光标都会添加一个“+”图标。但是,在 Drop 事件中,e.Effects 再次等于 DragDropEffects.All。为什么是这样?如何让 e.Effects 等于 Drop 事件中的不同内容?或者这有可能吗?

private static void dropTarget_Drop(object sender, DragEventArgs e)
{
    if (e.Effects == DragDropEffects.None || !e.Data.GetDataPresent(DataFormats.FileDrop))
        return;
    var effects = e.Effects;
    // effects == DragDropEffects.All, but I want it to have the Move or Copy flag removed
}

旁白:另一件事是我使用 Keyboard.IsKeyDown 而不是 e.KeyStates 因为 e.KeyStates 似乎总是相等DragDropKeyStates.LeftMouseButton。即使按下控件,DragDropKeyStates.ControlKey 位也始终为 0。知道这是为什么吗?

最佳答案

您应该将 DragOver 函数中的逻辑复制到 Drop 函数中,以再次确定效果。

您应该将其写回,而不是从 DragEventArgs 读取效果字段。该值被传回源,并且是函数 DoDragDrop 的返回值。

微软在中或多或少地描述了这一点 https://msdn.microsoft.com/en-us/library/ms742859%28v=vs.100%29.aspx ,但行为并不明显。我也犯了和你一样的错误。

关于c# - WPF DragDropEffects 在 Drop 事件中未正确设置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24688315/

相关文章:

c# - 将大量ID发送到SQL Server进行过滤时,有没有办法提高性能?

c# - SalesForce 查询方法不返回可用数据

c# - 生成的 C# 文件有哪些扩展名?

c# - 在 .Net 中实现优先级数组集合的最快(插入速度)方法是什么?

c# - 如何在 C# 中查找指数格式的字符串值?

WPF 数据网格样式

c# - WPF 绑定(bind) View 作为内容

c# - LINQ 为简单订单生成子查询

c# - 在 Windows Installer 中更改应用程序名称

c# - 为平台独立的字符串生成哈希码