我正在拖动项目以在WPF中制作FormBuilder。
我已经在画布上使用MouseLeftButtonDown和MouseMove事件实现了拖动。
我想使用MouseLeftButtonUp将项目移动到特定的StackPanel /画布中。
我需要在容器中获取此事件;我在目标Container上尝试过DragLeave和Drop,它们不会触发。
在MouseMove上,我总是将光标放在“拖动项”的中间,因此,在MouseUp上的目标容器上始终会有一个项。
如何将此项移至目标容器?
这是我的代码的某些部分:
private void MainCanvas_MouseMove(object sender, MouseEventArgs e)
{
if (e.LeftButton == MouseButtonState.Pressed)
{
if (MovingObject != null)
{
Point P = e.GetPosition(MainCanvas);
(MovingObject as FrameworkElement).SetValue(Canvas.LeftProperty, P.X - DeltaX);
(MovingObject as FrameworkElement).SetValue(Canvas.TopProperty, P.Y - DeltaY);
}
}
}
private void Button_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
if (sender is Draggable)
{
var Sender = (Draggable)sender;
PreviousParent = Sender.Parent as FrameworkElement;
if (PreviousParent is StackPanel)
{
((StackPanel)PreviousParent).Children.Remove(Sender);
Point Point = e.GetPosition(MainCanvas);
(Sender as FrameworkElement).SetValue(Canvas.LeftProperty, Point.X - Sender.ActualWidth/2);
(Sender as FrameworkElement).SetValue(Canvas.TopProperty, Point.Y - Sender.ActualHeight / 2);
MainCanvas.Children.Add(Sender);
}
MovingObject = Sender.ToDraggie();
}
else
{
MovingObject = sender;
}
FirstXPos = e.GetPosition(sender as Control).X;
FirstYPos = e.GetPosition(sender as Control).Y;
DeltaX = ((Control)sender).ActualWidth / 2;
DeltaY = ((Control)sender).ActualHeight / 2;
}
private void Button_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
MovingObject = null;
}