Drag and drop in WPF (and similar to Silverlight)

How do you do drag and drop in WPF?  Likely you haven’t given it much thought, lately, drag and drop just isn’t as cool when it first came out many years ago.  Back then, well, if you had drag and drop in your application, you were a genius.

In a WPF Application (I named mine, WPFDragDropExample), replace the <Grid> with the following:

    <Ellipse Name="greenie" Height="50" Width="50" Fill="Green"
         Canvas.Top="143" />
    <TextBox Background="Azure" Height="50" Width="50" Text="Blue"/>

In this a circular ellipse is set up AllowDrop and an event that will accept a Drop (event name: ellipse_Drop )

Now you need to add code to the code behind which is: MainWindow.xaml.cs

Add the following event method:

//*******************Start copy here *******************

private void ellipse_Drop(object sender, DragEventArgs e)
    Ellipse ellipse = sender as Ellipse;
    if (ellipse != null)
        // If the DataObject contains string data, extract it.
        if (e.Data.GetDataPresent(DataFormats.StringFormat))
            string dataString = (string)e.Data.GetData(DataFormats.StringFormat);

            // If the string can be converted into a Brush,
            // convert it and apply it to the ellipse.
            BrushConverter converter = new BrushConverter();
            if (converter.IsValid(dataString))
                Brush newFill = (Brush)converter.ConvertFromString(dataString);
                ellipse.Fill = newFill;

//*************End copy here ***********************

Now press F5 to run your code, select the word “Blue” in the textbox and drag it over to the ellipse, the ellipse will change to the color blue, in some configurations of the mouse settings you may need to click the primary mouse button (usually the left button) to make the drop complete.

Now type red in the textbox and drag it over to the ellipse, it will change colors again.

Kind of cool if you haven’t done this before.  You can do more with this by adding an icon for the drag from the textbox, etc.

Have fun.

Comments (0)

Skip to main content