Можно сделать так:
xaml code
<Grid AllowDrop="True">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<ListBox x:Name="listBox_main" Grid.Column="0" PreviewMouseDown="listBox_main_PreviewMouseDown" SelectionMode="Multiple">
<Image Source="Resources\1.jpg" Stretch="Uniform" Height="100" Width="100"></Image>
<Image Source="Resources\2.jpg" Stretch="Uniform" Height="100" Width="100"></Image>
<Image Source="Resources\3.jpg" Stretch="Uniform" Height="100" Width="100"></Image>
<Image Source="Resources\4.jpg" Stretch="Uniform" Height="100" Width="100"></Image>
<Image Source="Resources\5.jpg" Stretch="Uniform" Height="100" Width="100"></Image>
</ListBox>
<Canvas AllowDrop="True" Background="Transparent" x:Name="canvas_main" Grid.Column="1" DragEnter="canvas_main_DragEnter" Drop="canvas_main_Drop"
>
<Image Source="Resources\5.jpg" Stretch="Uniform" Height="100" Width="100"></Image>
</Canvas>
</Grid>
Code:
private void canvas_main_DragEnter(object sender, DragEventArgs e)
{
// Если пользователь копирует объект перетаскиванием и это список файлов и это не перетаскивание из listBox в него же
if (e.Data.GetDataPresent("MyappformatBitmapSource") &&
(e.AllowedEffects & DragDropEffects.Copy) != 0)
{
// Разрешить копирование
e.Effects = DragDropEffects.Copy;
}
}
private void canvas_main_Drop(object sender, DragEventArgs e)
{
// Если перетаскивается картинка
if (e.Data.GetDataPresent("MyappformatBitmapSource"))
{
foreach (BitmapSource bSource in (BitmapSource[])e.Data.GetData("MyappformatBitmapSource"))
{ // Показать картинку
Image new_image = new Image()
{
Source=bSource,
Stretch = Stretch.Uniform,
Width=100,
Height=100
};
canvas_main.Children.Add(new_image);
Canvas.SetLeft(new_image, 100);
Canvas.SetTop(new_image, 100);
}
}
}
private void listBox_main_PreviewMouseDown(object sender, MouseButtonEventArgs e)
{
// Создать контейнер для хранения данных
DataObject data = new DataObject();
if (listBox_main.SelectedItems.Count <= 0)
return;
// Положить содержимое выделенной в списке
BitmapSource[] col = new BitmapSource[listBox_main.SelectedItems.Count];
for(int i=0;i< listBox_main.SelectedItems.Count;i++)
{
if(listBox_main.SelectedItems[i] is Image image)
col[i]=(BitmapSource)image.Source;
};
// Добавить признак пользовательского формата в контейнер
data.SetData("MyappformatBitmapSource",col);
// НАЧАТЬ перетаскивание программно
DragDropEffects dde = DragDrop.DoDragDrop(this, data, DragDropEffects.Copy);
}