#695 – Implementing Drag-and-Drop Behavior

Below is code that implements some simple drag-and-drop behavior, dragging text from a TextBox to a ListBox.

In the XAML, we specify handlers for the MouseDown event on the TextBox and the Drop event on the ListBox.  We also set the AllowDrop property on the ListBox to true.

        <StackPanel Orientation="Vertical" Grid.Column="0" Margin="10">
            <Label Content="Enter some text and then drag to list"/>
            <TextBox Text="" MouseDown="txtMouseDown"/>
        <ListBox Grid.Column="1" Margin="10" AllowDrop="True" Drop="lbDrop"/>

In the MouseDown event handler for the TextBox, we initiate drag-and-drop using the DragDrop.DoDragDrop method.

        private void txtMouseDown(object sender, MouseButtonEventArgs e)
            TextBox txtElement = e.Source as TextBox;

            DragDrop.DoDragDrop(txtElement, txtElement.SelectedText, DragDropEffects.Copy);

In the Drop event handler for the ListBox, we get the data being dragged and add an item to the ListBox.

        private void lbDrop(object sender, DragEventArgs e)
            string draggedText = (string)e.Data.GetData(DataFormats.StringFormat);

            ListBox lbox = e.Source as ListBox;

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

One Response to #695 – Implementing Drag-and-Drop Behavior

  1. Pingback: Dew Drop – November 21, 2012 (#1,447) | Alvin Ashcraft's Morning Dew

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: