开发日常的Silverlight应用程序时,常常要对一个域多个控件实现可拖放的MOUSE操作,在Silverlight中实现拖放的功能其实非常简单,但是为了提高程序功能代码的可复用性,程序员常常喜欢把常用的代码封装成一个工具类,例如Asp.net中常用sqlHelper类,用来操作数据库的,这里我们介绍的类是在Silverlight中实现拖动的工具类,它支持Silverlight2.0至Silverlight4.0的各个版本通用,好了话不多说,我们还是看代码吧:
public static class DragDrop { private static bool IsDragging = false; private static Point curPoint; private const int MAX_ZINDEX = 99999; private const double CURRENT_OPACITY = 0.5; private static int lastZIndex; private static double lastOpacity; private static void sender_MouseLeftButtonDown(object sender,MouseButtonEventArgs e) { UIElement uiElement = sender as UIElement; if (uiElement != null) { uiElement.CaptureMouse(); lastZIndex = (int)uiElement.GetValue(Canvas.ZIndexProperty); uiElement.SetValue(Canvas.ZIndexProperty,MAX_ZINDEX); lastOpacity = uiElement.Opacity; uiElement.Opacity = CURRENT_OPACITY; IsDragging = true; curPoint = new Point(e.GetPosition(null).X,e.GetPosition(null).Y); } } private static void sender_MouseMove(object sender,MouseEventArgs e) { if (!IsDragging) { return; } UIElement uiElement = sender as UIElement; if (uiElement != null) { double currentLeft = (double)uiElement.GetValue(Canvas.LeftProperty); double currentTop = (double)uiElement.GetValue(Canvas.TopProperty); double newLeft = (double)currentLeft + e.GetPosition(null).X - curPoint.X; double newTop = (double)currentTop + e.GetPosition(null).Y - curPoint.Y; uiElement.SetValue(Canvas.LeftProperty,newLeft); uiElement.SetValue(Canvas.TopProperty,newTop); curPoint = new Point(e.GetPosition(null).X,e.GetPosition(null).Y); } } private static void sender_MouseLeftButtonUp(object sender,MouseButtonEventArgs e) { UIElement uiElement = sender as UIElement; if (uiElement != null) { uiElement.ReleaseMouseCapture(); IsDragging = false; uiElement.SetValue(Canvas.ZIndexProperty,lastZIndex); uiElement.Opacity = lastOpacity; } } public static void Load(UIElement sender) { sender.MouseLeftButtonDown += new MouseButtonEventHandler(sender_MouseLeftButtonDown); sender.MouseLeftButtonUp += new MouseButtonEventHandler(sender_MouseLeftButtonUp); sender.MouseMove += new MouseEventHandler(sender_MouseMove); } public static void UnLoad(UIElement sender) { sender.MouseLeftButtonDown -= new MouseButtonEventHandler(sender_MouseLeftButtonDown); sender.MouseLeftButtonUp -= new MouseButtonEventHandler(sender_MouseLeftButtonUp); sender.MouseMove -= new MouseEventHandler(sender_MouseMove); } } DragDrop工具类的使用方法:
DragDrop.Load(LayoutRoot);
DragDrop是一个静态类,使用起来非常简单,以上只要一行代码就可以实现对Grid控件的拖放操作了。
希望对大家有所帮助~!
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。