Google Search

Monday, April 6, 2009

Creating customizable WPF drop-down menus (3)


Step 3: Dragging items around


Once we have figured out how to detect the drag, we need to perform the actual dragging. Moreover, we want the menu to respond while we move around - hovering over a menu should cause it sub menu (if any) to open.

We will use the System.Windows.DragDrop helper class to perform the actual dragging.
The main method in the DragDrop class is DoDragDrop. This method is used to initialize a drag-and-drop session, perform the actual drag-and-drop operations, and returns the effect.

Initializing a drag-and-drop session


The DoDragDrop method takes 3 parameters:
  • A drag source (which will be our draggable menu item),
  • A data object, and
  • The allowed effects.

So as I mentioned, the drag source will be our draggable menu item. Since the code will be written as part of that menu item, we will just place there 'this'.
Our data source, while can be anything at all (as it is of type object), should be of type System.Windows.IDataObject, since otherwise it will be wrapped with a DataObject.
The best thing to do in this case would be to create a DataObject, and give it a unique name (or type), and the data itself. In our case, the data is the draggable menu item we'll be dragging, so the best unique id would be its type.
The only allowed effect, in our case, is the move effect, as this is what we want to do (at least for now) - move menu items from one place to another.

So if we implement the DoDragging method we left empty before:
private void DoDragging()
{
    IsDragging = true;
    DataObject dataObj = new DataObject(typeof(DraggableMenuItem), this);
    DragDrop.DoDragDrop(this, dataObj, DragDropEffects.Move);
    IsDragging = false;
}

Note that I raise the IsDragging flag before the dragging process begins, and lower it immediately afterwards. One reason for that is to prevent dragging to begin on other draggable menu items. Other reasons will become clear in the following posts.

No comments:

Post a Comment