Search code examples
c#wpfdrag-and-dropuielement

How do I keep the shape of an UIELement while doing a Drag and Drop in WPF


I have 2 StackPanels - one containing an Ellipse and the other one containing nothing.

I want to drag the Ellipse from one stack panel to the other. The actual drag & drop is already done and works fine, however I'd like to know how to keep that Ellipse shape at the tip of my mouse cursor.

Even a Windows Forms example would be nice, I'll be able to adapt it.


Solution

  • You want to add your drag adorner during the drag. I've seen this done a few different ways, but a quick search leads to this behavior, which has as nice a pattern as I've seen. A representative sample is:

        void itemsControl_PreviewDragEnter(object sender, DragEventArgs e)
        {
            ItemsControl itemsControl = (ItemsControl)sender;
            if (e.Data.GetDataPresent(ItemType))
            {
                object data = e.Data.GetData(ItemType);
                InitializeDragAdorner(itemsControl, data, e.GetPosition(itemsControl));
                InitializeInsertAdorner(itemsControl, e);
            }
            e.Handled = true;
        }
    

    They wrap up all the presentation of the drag adornment nicely in the DragAdorner class. (I wish I'd done mine this way, actually)

    I've also seen tricks with building the adornment out of a Visual Brush of the originally dragged element, but I think I like this approach best so far.

    BTW: After approaching this a few different times, I highly recommend wrapping your drag and drop code up into a behavior. Otherwise you wind up with it all over the place. Getting the commanding right with MVVM can be quite tricky, but it's worth it, IMHO.