c# wpf 实现拖动图片功能

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


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值