我正在尝试在WPF中实现拖放。我现在的代码允许我点击按钮的左上角并向下或向右拖动。
出于某种原因,它不允许我向左或向上拖动,我无法弄清楚原因。
代码如下:
private void ctlTextbox_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
//In this event, we get current mouse position on the control to use it in the MouseMove event.
FirstXPos = e.GetPosition(sender as Control).X;
FirstYPos = e.GetPosition(sender as Control).Y;
FirstArrowXPos = e.GetPosition((sender as Control).Parent as Control).X - FirstXPos;
FirstArrowYPos = e.GetPosition((sender as Control).Parent as Control).Y - FirstYPos;
}
private void ctlTextbox_MouseMove(object sender, MouseEventArgs e)
{
if (e.LeftButton == MouseButtonState.Pressed)
{
(sender as FrameworkElement).SetValue(Canvas.LeftProperty,
e.GetPosition((sender as FrameworkElement).Parent as FrameworkElement).X - FirstXPos);
(sender as FrameworkElement).SetValue(Canvas.TopProperty,
e.GetPosition((sender as FrameworkElement).Parent as FrameworkElement).Y - FirstYPos);
}
}
XAML:
<Canvas x:Name="MainGrid" RenderTransformOrigin = "0.499,0.425" AllowDrop="True" >
<Button x:Name="button" Content="112" Style="{StaticResource RoomButton}" MouseLeftButtonDown="ctlTextbox_MouseLeftButtonDown" MouseMove="ctlTextbox_MouseMove" Height="32" Canvas.Left="69" Canvas.Top="67" Width="65" Margin="0" />
</Canvas>
答案 0 :(得分:0)
尝试以下方式:
在_movingObject
中添加名为Window
的私人字段:
private FrameworkElement _movingObject;
将您的XAML修改为:
<Canvas x:Name="MainGrid" RenderTransformOrigin = "0.499,0.425" AllowDrop="True"
Background="Transparent" PreviewMouseMove="CanvasPreviewMouseMove">
<Button x:Name="button" Style="{StaticResource RoomButton}"
PreviewMouseLeftButtonDown="UIElementPreviewMouseLeftButtonDown"
PreviewMouseLeftButtonUp="UIElementPreviewMouseLeftButtonUp"
Height="32" Canvas.Left="69" Canvas.Top="67" Width="65" Margin="0" />
</Canvas>
在代码隐藏中添加以下处理程序:
private void UIElementPreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
_movingObject = sender as FrameworkElement;
}
private void UIElementPreviewMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
_movingObject = null;
}
private void CanvasPreviewMouseMove(object sender, MouseEventArgs e)
{
var mousePos = e.GetPosition(sender as IInputElement);
if (e.LeftButton == MouseButtonState.Pressed && _movingObject != null)
{
_movingObject.SetValue(Canvas.LeftProperty, mousePos.X);
_movingObject.SetValue(Canvas.TopProperty, mousePos.Y);
}
}
问题在于,当您向上移动鼠标或向左移动鼠标时,您将其移动到您尝试拖动的控件的边界之外,因此其MouseMove
事件未被调用。