需求:使得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;
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;
}
|
请发表评论