【WPF/C#】拖拽Image图片控件

需求:使得Image图片控件能够被拖动。

思路:关键是重写Image控件的几个鼠标事件,实现控制。

前台:

<Image 
    Source="C:\Users\Administrator\Documents\Visual Studio 2015\Projects\WpfApplication1\WpfApplication1\Resources\Images\Application.ico"
    MouseLeftButtonUp="Image_MouseLeftButtonUp" 
    MouseLeftButtonDown="Image_MouseLeftButtonDown" 
    MouseMove="Image_MouseMove"/>

后台:

private void Image_MouseMove(object sender, MouseEventArgs e)
{
    if (isDown)
    {
        Image image = e.Source as Image;
        // 因为Image图片的原点位于它的左上角而非中心点,所以还需要减去自身宽高的一半
        Canvas.SetLeft(image, e.GetPosition(canvas).X - image.ActualWidth/2);
        Canvas.SetTop(image, e.GetPosition(canvas).Y - image.ActualHeight/2);
    }
}

private void Image_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
    isDown = true;
}

private void Image_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
    isDown = false;
}
posted @ 2017-03-20 09:56  霍莉雪特  阅读(2919)  评论(1编辑  收藏  举报