Welcome

首页 / 软件开发 / Silverlight / Silverlight & Blend动画设计系列八:拖放(Drag-Drop)操作与拖放行为

Silverlight & Blend动画设计系列八:拖放(Drag-Drop)操作与拖放行为2011-04-20 博客园 Beniao在Silverlight中自身并没有提供拖放功能的相关实现,要实现拖放功能得借助其事件支 持(MouseLeftButtonDown、 MouseLeftButtonUp和MouseMove)来完成,实际应用中我们可 以通过行为(Behavior)特性将拖放操作封装为行为,这样可达到代码复用的效果。而在 Blend中则直接提供了拖放操作行为,它位于Microsoft.Expression.Interactions.dll的 Microsoft.Expression.Interactivity.Layout名称空间下。

Silverlight中的拖放操作通常是使用事件驱动动态定位对象的坐标来实现,首先来看看 如何通过代码的可编程方式在Silverlight中实现拖放操作,如下代码块:

private void OnMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
FrameworkElement element = sender as FrameworkElement;
MousePosition = e.GetPosition(null);
IsMouseCaptured = true;
element.CaptureMouse();
element.Cursor = Cursors.Hand;
}
private void OnMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
FrameworkElement element = sender as FrameworkElement;
IsMouseCaptured = false;
element.ReleaseMouseCapture();
MousePosition.X = MousePosition.Y = 0;
element.Cursor = null;
}
private void OnMouseMove(object sender, MouseEventArgs e)
{
FrameworkElement element = sender as FrameworkElement;
if (IsMouseCaptured)
{
double Y = e.GetPosition(null).Y - MousePosition.Y;
double X = e.GetPosition(null).X - MousePosition.X;
X = X + (double)element.GetValue(Canvas.LeftProperty);
Y = Y + (double)element.GetValue(Canvas.TopProperty);
element.SetValue(Canvas.LeftProperty, X);
element.SetValue(Canvas.TopProperty, Y);
MousePosition = e.GetPosition(null);
}
}

如上定义好的三个方法实现了对象的拖放算法,实际应用中只需要将需要进行拖放移动的 对象分别添加MouseLeftButtonDown、MouseLeftButtonUp和MouseMove事件处理就行了。如下 示例代码:

attachedElement.MouseLeftButtonDown += (s, e) => OnMouseLeftButtonDown(s, e);
attachedElement.MouseLeftButtonUp += (s, e) => OnMouseLeftButtonUp(s, e);
attachedElement.MouseMove += (s, e) => OnMouseMove(s, e);

按照常规做法我们会将以上相关方法的实现封装为一个基类以达到复用的目的,但本文不 推荐使用基类去封装拖放行为,因为Silverlight有专门用于处理对象行为的特性-Behaviors 。在Silverlight中System.Windows.Interactivity命名空间下提供了行为的基础框架,我们 可以进行自由的扩展行为以实现自己的不同需求。安装Blend后可以在安装目录下找到 Microsoft.Expression.Interactivity.dll这个库,这个库提供了一些比较常用的集中行为 扩展,在Blend中通过 “窗口”--“资产”打开资产面板,选择行为资产就可以查看到 Silverlight 3中所提供的扩展行为,如下图: