#702 – Dragging an Image within a WPF Application

You can drag the contents of one Image control onto another Image control fairly easily.  When you drag an image to another application, you have to convert the image to a bitmap.  But within the same application, you can just use the value of the image’s Source property as the data being dragged.

    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition/>
            <ColumnDefinition/>
        </Grid.ColumnDefinitions>

        <Image Grid.Column="0" Source="Life01.jpg" Stretch="None" Margin="10"
                MouseLeftButtonDown="Image_MouseLeftButtonDown"/>
        <Image Grid.Column="1" Margin="10" AllowDrop="True" Drop="Image_Drop" Source="DropHere.png" />
    </Grid>

 

        private void Image_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            Image img = e.Source as Image;
            DataObject data = new DataObject(DataFormats.Text, img.Source);

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

        private void Image_Drop(object sender, DragEventArgs e)
        {
            Image img = e.Source as Image;
            img.Source = (BitmapSource) e.Data.GetData(DataFormats.Text);
        }


Advertisement

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

One Response to #702 – Dragging an Image within a WPF Application

  1. Pingback: Dew Drop – November 30, 2012 (#1,453) | 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 )

Facebook photo

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

Connecting to %s

%d bloggers like this: