在运行时拖动窗体上的控件

时间:2010-05-11 14:59:27

标签: c# wpf windows controls drag-and-drop

我刚刚开始使用WPF。但我正在尝试添加我的代码(来自Winforms),用户可以在运行时随意拖动任何控件。但我似乎无法获得鼠标的当前位置......呃?鼠标没有位置? :(

3 个答案:

答案 0 :(得分:2)

在鼠标事件中,您可以使用e.GetPosition获取当前鼠标位置。此函数可以提供相对于特定元素的鼠标位置,或者您可以只传递null。

这是一个非常简单的例子,没有命中测试或任何东西,只是一个可以拖动的按钮。我使用画布来缩短它,但你最好使用变换并将控件转换到所需的位置。

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Canvas PreviewMouseLeftButtonDown="Canvas_PreviewMouseLeftButtonDown" 
            PreviewMouseMove="Canvas_PreviewMouseMove" 
            PreviewMouseLeftButtonUp="Canvas_PreviewMouseLeftButtonUp">
        <Button Name="dragButton" Width="80" Height="21" Canvas.Left="50" Canvas.Top="10">Drag Me!</Button>
    </Canvas>
</Window>


using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;

namespace WpfApplication1
{
  public partial class MainWindow : Window
  {
    public MainWindow()
    {
      InitializeComponent();      
    }    

    private Point _startPoint;
    private bool _dragging = false;

    private void Canvas_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
    {         
      if (dragButton.CaptureMouse())
      {        
        _startPoint = e.GetPosition(null);
        _dragging = true;        
      }
    }

    private void Canvas_PreviewMouseMove(object sender, MouseEventArgs e)
    {
      if (_dragging)
      {        
        Point newPoint = e.GetPosition(null);
        double dx = newPoint.X - _startPoint.X;
        double dy = newPoint.Y - _startPoint.Y;

        Canvas.SetLeft(dragButton, Canvas.GetLeft(dragButton) + dx);
        Canvas.SetTop(dragButton, Canvas.GetTop(dragButton) + dy);
        _startPoint = newPoint;
      }
    }

    private void Canvas_PreviewMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
    {
      if (_dragging)
      {        
        _dragging = false;
        dragButton.ReleaseMouseCapture();
      }
    }    
  }
}

答案 1 :(得分:0)

我认为在WPF中获取此信息的方法是使用一些附加事件。您可以进入PreviewMouseDown,PreviewMouseMove和PreviewMouseUp的事件处理程序,以获取有关鼠标超过某些控件并且用户按下/释放鼠标按钮,移动鼠标等的信息。

这里有一个很好的实例:Generic WPF Drag-and-Drop Adorner

答案 2 :(得分:0)

我不知道为什么它不正确,但是对我有用。

private void Button_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
    moving = true;
}

private void Button_PreviewMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
    moving = false;
}

private void Button_PreviewMouseMove(object sender, MouseEventArgs e)
{
    if (moving)
    {
        Canvas.SetTop(this, e.GetPosition(Parent as Canvas).Y);
        Canvas.SetLeft(this, e.GetPosition(Parent as Canvas).X);
    }
}