开发者

Obtaining DoDragDrop DragSource

The WPF DragDrop.DoDragDrop method has DragSource as i开发者_如何学Gots first parameter.

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


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 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:

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);

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));

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜