这个示例程序最大的特点是能在遮罩块内对图形对象进行拖动,这是通过编程实现的。为了能在C#代码中引用图形对象,必须为每个图形对象的x:Name指定一个对象名称。
由于要拖动图形,因此这个样例的编程将需要处理鼠标事件。在第6章6.1.4小节曾经举过一个画布拖动的例子,本节的样例与此类似,代码如下所示。
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
namespace ScrollImpage
{
public partial class Page : Canvas
{
//布尔值,检查鼠标是否在按下拖动。
bool bMoving;
//保存上一个鼠标点的坐标位置
Point pPrevPoint;
//用于保存图片的坐标位置。
Point pLTImage = new Point(-200, -200);
public void Page_Loaded(object o, EventArgs e)
{
// Required to initialize variables
InitializeComponent();
//初始化所需要的四个事伯。
window.MouseLeave += new EventHandler(window_MouseLeave);
img.MouseLeftButtonDown += new MouseEventHandler(img_MouseLeftButtonDown);
img.MouseMove += new MouseEventHandler(img_MouseMove);
img.MouseLeftButtonUp += new MouseEventHandler(img_MouseLeftButtonUp);
}
void img_MouseLeftButtonUp(object sender, MouseEventArgs e)
{
//如果在图像内释放鼠标,则将bMoving设置为Flase,停止拖动。
bMoving = false;
}
void img_MouseMove(object sender, MouseEventArgs e)
{
if (bMoving)
{
//当拖动鼠标时,首先获取当前坐标值。
double X = e.GetPosition(window).X;
double Y = e.GetPosition(window).Y;
//计算当前坐标与鼠标上一次的位置之间的差距。
double deltaX = X - pPrevPoint.X;
double deltaY = Y - pPrevPoint.Y;
//将当前鼠标位置保存。
pPrevPoint = new Point(X, Y);
//调整图片的坐标。
pLTImage.X = Math.Min(pLTImage.X + deltaX, 0);
pLTImage.X = Math.Max(pLTImage.X, -(img.Width - window.Width));
pLTImage.Y = Math.Min(pLTImage.Y + deltaY, 0);
pLTImage.Y = Math.Max(pLTImage.Y, -(img.Height - window.Height));
img.SetValue<double>(Canvas.LeftProperty, pLTImage.X);
img.SetValue<double>(Canvas.TopProperty, pLTImage.Y);
}
}
void img_MouseLeftButtonDown(object sender, MouseEventArgs e)
{
//保存最初的鼠标位置,并开始鼠标拖动。
double X = e.GetPosition(window).X;
double Y = e.GetPosition(window).Y;
pPrevPoint = new Point(X, Y);
bMoving = true;
}
void window_MouseLeave(object sender, EventArgs e)
{
//如果在画布内释放鼠标,则将bMoving设置为Flase,停止拖动。
bMoving = false;
}
}
}
运行这个示例程序,在图形中拖动鼠标,则图片会自动的调整位置,如图所示。