开发日常的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 stati
c int lastZIndex;
private static double lastOpacity;
private static void sender_Mou
SELEftButtonDown(ob
ject sender,MouseButtonEventArgs
E)
{
UIElement uiElement = sender as UIElement;
if (uiElement
!= null)
{
uiElement.CaptureMouse(
);
lastZIndex = (
int)uiElement.GetValue(Canva
s.ZIndexProperty
);
uiElement.
SETVALue(Canva
s.ZIndexProperty,MAX_ZINDE
X);
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(ob
ject sender,MouseEventArgs
E)
{
if (!IsDragging)
{
return;
}
UIElement uiElement = sender as UIElement;
if (uiElement
!= null)
{
double currentLeft = (doubl
E)uiElement.GetValue(Canva
s.LeftProperty
);
double currentTop = (doubl
E)uiElement.GetValue(Canva
s.TopProperty
);
double newLeft = (doubl
E)currentLeft + e.GetPosition(null).X - curPoint.X;
double newTop = (doubl
E)currentTop + e.GetPosition(null).Y - curPoint.Y;
uiElement.
SETVALue(Canva
s.LeftProperty,newLeft
);
uiElement.
SETVALue(Canva
s.TopProperty,newTo
p);
curPoint = new Point(e.GetPosition(null).X,e.GetPosition(null).Y
);
}
}
private static void sender_Mou
SELEftButtonUp(ob
ject sender,MouseButtonEventArgs
E)
{
UIElement uiElement = sender as UIElement;
if (uiElement
!= null)
{
uiElement.ReleaseMouseCapture(
);
IsDragging =
false;
uiElement.
SETVALue(Canva
s.ZIndexProperty,lastZInde
X);
uiElement
.opacity = lastOpacity;
}
}
public static void Load(UIElement sender)
{
sender.Mou
SELEftButtonDown += new MouseButtonEventHandler(sender_Mou
SELEftButtonDown
);
sender.Mou
SELEftButtonUp += new MouseButtonEventHandler(sender_Mou
SELEftButtonU
p);
sender.MouseMove += new MouseEventHandler(sender_MouseMov
E);
}
public static void UnLoad(UIElement sender)
{
sender.Mou
SELEftButtonDown -= new MouseButtonEventHandler(sender_Mou
SELEftButtonDown
);
sender.Mou
SELEftButtonUp -= new MouseButtonEventHandler(sender_Mou
SELEftButtonU
p);
sender.MouseMove -= new MouseEventHandler(sender_MouseMov
E);
}
}
DragDrop工具类的使用
方法:DragDrop.Load(LayoutRoot
);DragDrop是
一个静态类,使用起来非常简单,以上只要一行
代码就可以实现对Grid控件的拖放操作了。希望对大家有所帮助~!