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


Advertisements