クラスをドラッグ

3124 ワード

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);