#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;