1)前台
<Window x:Class="DragAndDropDemo.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="600" Width="800">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="100"></RowDefinition>
<RowDefinition Height="auto"></RowDefinition>
</Grid.RowDefinitions>
<StackPanel Grid.Row="0" Orientation="Horizontal">
<Image Source="/DragAndDropDemo;component/image/img_1.jpg" Width="100" Height="100" MouseDown="Image_MouseDown" Cursor="Hand" />
<Image Source="/DragAndDropDemo;component/image/img_2.jpg" Width="100" Height="100" MouseDown="Image_MouseDown" Cursor="Hand" />
<Image Source="/DragAndDropDemo;component/image/img_3.jpg" Width="100" Height="100" MouseDown="Image_MouseDown" Cursor="Hand" />
<Image Source="/DragAndDropDemo;component/image/img_4.jpg" Width="100" Height="100" MouseDown="Image_MouseDown" Cursor="Hand" />
</StackPanel>
<Image Width="400" Height="400" Grid.Row="2" AllowDrop="True" Drop="Image_Drop" Source="/DragAndDropDemo;component/image/img_1.jpg" />
</Grid>
</Window>
2)后台
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace DragAndDropDemo
{
/// <summary>
/// Window1.xaml 的交互逻辑
/// </summary>
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
}
/// <summary>
/// 按下鼠标复制源Image控件的source。
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Image_MouseDown(object sender, MouseButtonEventArgs e)
{
Image image = (Image)sender;
DragDrop.DoDragDrop(image, image.Source, DragDropEffects.Copy);
}
/// <summary>
/// 当源Image控件中的图片拖到目标Image控件中,
/// 将源Image控件的source赋值给目标Image控件。
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Image_Drop(object sender, DragEventArgs e)
{
//如果你不知道获取的数据的格式用e.Data.GetFormats();获取。
((Image)sender).Source = (ImageSource)e.Data.GetData("System.Windows.Media.Imaging.BitmapFrameDecode");
}
}
}