#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