WPF drag-and-drop function implementation

Source: Internet
Author: User

Preface: This article is made for impromptu purposes, so it is inevitable that there are omissions and bad words. We look forward to your comments and sharing your thoughts and suggestions.

This is a short article about how to implement the drag-and-drop function in WPF.

The first thing you need to know is that drag and drop mainly consists of Drag and Drop sources and drag and drop targets. Drag-and-drop sources and drag-and-drop targets each have different events. Software developers need to complete relevant functions in appropriate events.

Imagine how Drag and Drop Operations: the user selects an interface element, moves the mouse with the left mouse button pressed, and finally opens the left mouse button when reaching the drag and drop target, this completes the entire process of data drag and drop. SlaveProgramFrom the writing point of view, you need to move the selected project with the left-click button to start drag-and-drop, and give the appearance feedback of the current drag-and-drop status while moving the mouse, when you release the mouse, try to add the project to the target.

For any software interface, clicking and moving with the left mouse button does not necessarily lead to the start of the drag-and-drop operation. Therefore, software developers need to writeCodeStart the drag-and-drop function, not determined by WPF. This is why software developers need to manually call dragdrop. dodragdrop () under specific conditions to start the drag-and-drop operation. The dragdrop. dodragdrop () function accepts three parameters: dragsource, data, and allowedeffects. Note the dragsource parameter. This parameter indicates the message source of the drag-and-drop operation and determines who sends all the message source events. The data parameter is used to wrap the data operated by Drag & drop. Generally, it is a dataobject instance. The actual operation data of the instance should be packed and dragged. Finally, allowedeffects can be used to specify the effect of the drag operation. The code snippet that calls this function can be as follows:

 
1Dragdrop. dodragdrop (mlistbox, dataobject, dragdropeffects. copy );

After the drag operation is started, software developers need to handle a series of events that occur during the drag operation. In this case, software developers cannot expect to complete the drag-and-drop response by responding to events such as mouse. mousemove. This is because the dragdrop. dodragdrop () function is actually a blocking function. These events will not be sent until the drag-and-drop action ends. Instead, software developers can use the drag-and-drop events provided by the source and target. The events provided by the drag-and-drop source are querycontinuedrag, givefeedback, and the corresponding preview-events. The querycontinuedrag event is used to determine whether to continue the drag-and-drop operation. This event occurs when the status of the keyboard or mouse button changes. Givefeedback is used to provide users with drag-and-drop feedback information, such as making the image of the dragged interface element change with the mouse, or providing a tooltip to indicate the user's current drag-and-drop effect. The message is regularly sent during the drag and drop process. Therefore, software developers can use the message as a timer event. It is important to understand the timing of drag-and-drop events because software developers cannot use other events during the drag-and-drop process.

In addition, when you see the preview-event, we believe you will be able to think of it as a tunnel/bubble routing event. Therefore, to process these events, you do not need to add event processing functions to the drag-and-drop source. You can rewrite the corresponding functions at a higher level, for example, override the ongivefeedback () function of window. The advantage of this is that it provides a concentrated drag-and-drop processing logic and has good semantic features when you need to change high-level interface elements, such as the status bar of a window. This method is not suitable for windows with multiple drag-and-drop sources. Of course, it is also a good choice to listen to messages sent from the source at a high level.

If we need to implement the preview function of the drag and drop interface elements, the implementation of this function is as follows:

 1 Mlistbox. previewmousemove + = onpreviewlistboxmousemove;
2 Mlistbox. querycontinuedrag + = onquerycontinuedrag;
3
4 Private Void Onquerycontinuedrag ( Object Sender, querycontinuedrageventargs E)
5 {
6 Madornerlayer. Update ();
7 ...
8 }
9
10 Private Void Onpreviewlistboxmousemove ( Object Sender, mouseeventargs E)
11 {
12 Listboxitem =... // Find your actual visual you want to drag
13 ...
14 Dragdropadorner adorner = New Dragdropadorner (listboxitem );
15 Madornerlayer = adornerlayer. getadornerlayer (mtoplevelgrid );
16 Madornerlayer. Add (adorner );
17
18 Dataitem = listboxitem. Content As Dataitem;
19 Dataobject = New Dataobject (dataitem. Clone ());
20 // Here, we shoshould notice that dragsource param will specify on which
21 // Control the drag & Drop event will be fired
22 System. Windows. dragdrop. dodragdrop (mlistbox, dataobject, dragdropeffects. copy );
23 ...
24 }

Dragdropadorner is used to display the preview of the dragged interface element. It uses adorner. If you are interested in the implementation of this control, download the sample program to view it. For the use of adorner, I will write a special article at the time.Article.

Next, drag the target event. The dragenter, dragover, dragleave, drop, and preview-events are sent to the drag target. The meaning of these events is very clear, and you can see the timing of these events from the name. In these events, you must note the input drageventargs. By setting its effects members, software developers can control the mouse status to prompt users with cursor feedback for the current drag action. In addition, with its data attribute, software developers can obtain the data passed in when the dodragdrop () function is called.

The following code responds to the drag and drop target event:

 1   Private   Void Ondragover ( Object Sender, drageventargs E)
2 {
3 E. effects = dragdropeffects. None;
4
5 // Find the corresponding Treeview item in mtreeview and select it
6 Point Pos = E. getposition (mtreeview );
7 Hittestresult result = visualtreehelper. hittest (mtreeview, POS );
8 If (Result = Null )
9 Return ;
10
11 Treeviewitem selecteditem = utils. findvisualparent <treeviewitem> (result. visualhit );
12 If (Selecteditem! =Null )
13 Selecteditem. isselected = True ;
14
15 E. effects = dragdropeffects. copy;
16 }
17
18 Private Void Ondrop ( Object Sender, drageventargs E)
19 {
20 // Drop the data item into corresponding Treeview item
21 Point Pos = E. getposition (mtreeview );
22 Hittestresult result = visualtreehelper. hittest (mtreeview, POS );
23 If (Result = Null )
24 Return ;
25
26 Treeviewitem selecteditem = utils. findvisualparent <treeviewitem> (result. visualhit );
27 If (Selecteditem = Null )
28 Return ;
29
30 Dataitem parent = selecteditem. Header As Dataitem;
31 Dataitem = E. Data. getdata ( Typeof (Dataitem )) As Dataitem;
32 If (Parent! = Null & Dataitem! = Null )
33 Parent. Items. Add (dataitem );
34 }

You need to pay attention to the call to the getdata () function in this section of code. In the drag & Drop Process, if you want to obtain data from dataobject, you must use the original type. For example, if A is a base class of B and dataobject is an instance of type B, the software developer must. getdata () uses typeof (B) instead of typeof ().

When implementing the drag-and-drop function, software developers need to pay attention to a series of issues.

First, dragdropeffect. Each value in this enumeration corresponds to a specific behavior in the drag-and-drop process. These appearances have specific usage in the UI design and user use. Therefore, in the development process, you need to determine what operations you want to perform on the drag-and-drop target to prevent users' doubts during use.

In addition, the external Drag Source is also a common drag function, such as dragging files to the application for loading. In some cases, dragging a target event does not provide the required information. For example, when you drag multiple files to an application, the idataobject interface only provides the getdata () function. In this case, software developers can try to convert it to a dataobject type instance and return all the dragged files through the getfiledroplist () function.

At the same time, you must pay attention to the method for obtaining the mouse position. During the Drag and Drop Process, the mouse position cannot be obtained through standard methods such as the mouse class. In some cases, this method returns an incorrect location. This is because the control of the mouse is managed by the drag source during the drag process. The Win32 function is used during the management process, so that WPF cannot return the mouse position information correctly. A work und is to use pinvoke to call Win32 API getcursorpos ().

Another tips to mention is how to disable drag. Standard controls include controls that can be used as drag targets by default, such as textbox. To disable this function, software developers can set the handled attribute of drageventargs in the onpreviewdragenter () and onpreviewdragover () overload to true, and set effects to none to simulate the effect of prohibiting drag and drop.

 

Source code download: http://download.csdn.net/detail/silverfox715/3884722

Reprinted please indicate the original address: http://www.cnblogs.com/loveis715/archive/2011/12/05/2277384.html

Business reprint please contact me in advance: silverfox715@sina.com

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.