#706 – Dragging User Interface Elements Between Applications

You can drag user interface elements between WPF applications using drag-and-drop.  To do this, you read the XAML for the portion of the logical tree that you want to drag and specify XAML as your data format.

The example below shows how to drag a StackPanel and everything in it from one application to another.

On the drag side, we use a XamlWriter object to store all of the XAML into a string.

        private void StackPanel_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            string xaml = XamlWriter.Save(e.Source);
            DataObject data = new DataObject(DataFormats.Xaml, xaml);

            DragDrop.DoDragDrop((DependencyObject)e.Source, data, DragDropEffects.Copy);
        }

On the drop side, we use a XamlReader to load the data back into the application.  In this example, we set the StackPanel as the main content for the Window that we’re dragging it to.

        private void Window_Drop(object sender, DragEventArgs e)
        {
            string xaml = (string)e.Data.GetData(DataFormats.Xaml);
            this.Content = XamlReader.Load(new XmlTextReader(new StringReader(xaml)));
        }

706-001
706-002
706-003

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 #706 – Dragging User Interface Elements Between Applications

  1. Pingback: Dew Drop–December 6, 2012 (#1,457) | 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: