获取 DoDragDrop DragSource [英] Obtaining DoDragDrop DragSource

查看:15
本文介绍了获取 DoDragDrop DragSource的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

WPF DragDrop.DoDragDrop 方法的第一个参数是 DragSource.

The WPF DragDrop.DoDragDrop method has DragSource as its first parameter.

有没有办法在OnDrop或其他拖放事件中获取这个DragSource对象?

Is there a way you can obtain this DragSource object in the OnDrop or other drag and drop events?

推荐答案

简短的回答是否定的,因为当您收到 Drag 事件(或 DragEnter 等)时,拖动源对象可能在任何地方.它可能在另一个过程中.它可以是本机代码.如果类似 RDP 的协议足够复杂,可以处理它,它甚至可以在另一台机器上.换句话说,甚至不能保证托管的 DoDragDrop 被调用,如果是,则不能保证它是从这个进程调用的.

The short answer is no, because when you receive a Drag event (or DragEnter, etc) the drag source object could be anywhere. It could be in another process. It could be in native code. It could even be on another machine if a RDP-like protocol is sophisticated enough to handle it. In other words there is no guarantee the managed DoDragDrop was even called, and if it was there is no guarantee it was called from this process.

BUT 如果您正在编写调用 DoDragDrop 的代码并同时编写 OnDrop() 的代码,那么有一个简单的方法要获得这种效果:

BUT if you are writing the code that calls DoDragDrop and are also writing the code for OnDrop(), there is an easy way to get this effect:

在对 DoDragDrop 的调用中,将您的对象添加为额外格式:

In the call to DoDragDrop, add your object as an extra format:

 var dragSource = this;
 var data = "Hello";

 var dataObj = new DataObject(data);
 dataObj.SetData("DragSource", dragSource);
 DragDrop.DoDragDrop(dragSource, dataObj, DragDropEffects.Copy);

现在在 OnDrag 处理程序中很容易获得拖动源:

Now in the OnDrag handler it is easy to get the drag source:

protected override void OnDrop(DragEventArgs e)
{
  var data = e.Data.GetData(DataFormats.Text);
  var dragSource = e.Data.GetData("DragSource");
  ...
}

在某些情况下,知道源对象本身就足以获取完成拖动操作所需的数据,在这种情况下,上述情况归结为:

In some cases, knowing the source object itself is sufficient to get the data you require to complete the drag operation, in which case the above boils down to:

 DragDrop.DoDragDrop(dragSource, dragSource, DragDropEffects.Copy);

 ...

 var dragSource = e.Data.GetData(typeof(MyDragSource));

请注意,在这两种情况下,如果拖动操作的来源不是您的代码(例如从 Emplorer 拖动文件),您将得到 dragSource=null

Note that in either of these cases, if the source of the drag operation is somewhere other than your code (eg dragging a file from Emplorer), you will get dragSource=null

这篇关于获取 DoDragDrop DragSource的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆