实现鼠标 down 、 up 和 move 事件可以在布局面板中使用鼠标拖动或移动嵌套在Border控件中的图像或对象。
看 .xaml 代码:
< Canvas x : Name ="LayoutRoot" Background ="White">
<Borderx : Name ="border1"
Canvas.Top ="100"
Canvas.Left ="10"
MouseLeftButtonDown ="border1_MouseLeftButtonDown"
MouseLeftButtonUp ="border1_MouseLeftButtonUp"
MouseMove ="border1_MouseMove">
<Imagex : Name ="MyImage" Source ="images/Basket.png"
Stretch="Uniform" ></Image >
</Border>
</ Canvas >
在上面代码中, Border 控件放置在 Canvas中,值得注意的重要代码是:
MouseLeftButtonDown ="border1_MouseLeftButtonDown"
MouseLeftButtonUp ="border1_MouseLeftButtonUp"
MouseMove ="border1_MouseMove"
上面代码行定义了需要处理 的 3 个事 件。正如其名称所示,需要处理左鼠标按下事件、左鼠标单击并放开事件和左鼠标移动事件。
在后置代码中,当左鼠标按 下,将设置一个全局变量用来标识用户开始移动。在鼠标移到时间,将设置一个鼠标当前位置并为Border控件设置新位置。当左鼠标释放时,将重设全局变量以便不会移动更多的对象。
看后置代码:
public partial class Page : UserControl {
// Global variable to indicate if user has clicked border
// and started/stopped moving.
private bool moving = false ;
private double offSetX;
private double offSetY;
public Page() {
InitializeComponent();
}
private void border1_MouseLeftButtonDown(object sender,
MouseButtonEventArgs e) {
// Left mouse button clicked within border. start moving.
moving = true ;
Point offset = e.GetPosition(border1);
offSetX = offset.X;
offSetY = offset.Y;
}
private void border1_MouseLeftButtonUp(object sender,
MouseButtonEventArgs e) {
// Left mouse button release. Stop moving.
moving = false ;
}
private void border1_MouseMove(object sender,MouseEventArgs e) {
if (moving) {
// Get the new mouse pointer position
Canvas parent = (Canvas )this .border1.Parent;
Point p = e.GetPosition(parent);
double x = p.X - offSetX;
double y = p.Y - offSetY;
// Set the new position for the border control.
this .border1.SetValue(Canvas .LeftProperty, x);
this .border1.SetValue(Canvas .TopProperty, y);
}
}
}
Silverlight入门知识学习目录