September 5, 2008

Canvas上のオブジェクトをドラッグ&ドロップ

Canvasの上にあるオブジェクトをドラッグ&ドロップする。

How to: Drag and Drop Objects

Silverlight / WPF

        #region Handle
bool isMouseCaptured;
Point mousePosition;

void HandleMouseDown(object sender, MouseButtonEventArgs e)
{
FrameworkElement item = sender as FrameworkElement;
mousePosition = e.GetPosition(null);
isMouseCaptured = true;
item.CaptureMouse();
item.Cursor = Cursors.Hand;

e.Handled = true;
}
void HandleMouseMove(object sender, MouseEventArgs e)
{
FrameworkElement item = sender as FrameworkElement;
if (isMouseCaptured)
{
// Calculate the current position of the object.
double deltaV = e.GetPosition(null).Y - mousePosition.Y;
double deltaH = e.GetPosition(null).X - mousePosition.X;
double newTop = deltaV + (double)item.GetValue(Canvas.TopProperty);
double newLeft = deltaH + (double)item.GetValue(Canvas.LeftProperty);

// Set new position of object.
item.SetValue(Canvas.TopProperty, newTop);
item.SetValue(Canvas.LeftProperty, newLeft);

// Update position global variables.
mousePosition = e.GetPosition(null);
}

e.Handled = true;
}
void HandleMouseUp(object sender, MouseButtonEventArgs e)
{
FrameworkElement item = sender as FrameworkElement;
isMouseCaptured = false;
item.ReleaseMouseCapture();
mousePosition.X = mousePosition.Y = 0;
item.Cursor = null;

e.Handled = true;
}
#endregion