在运行时拖动表格控件 [英] Dragging Controls on Form at runtime

查看:115
本文介绍了在运行时拖动表格控件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚开始使用WPF。但我想加我的代码(从的WinForms)使用户可以拖动等。无论他们希望在运行任何控制。但我似乎无法得到鼠标的当前位置...咦?没有定位的鼠标? :(

I've just started using WPF. But I'm trying to add my code that (from Winforms) enables the user to drag any control whereever they wish at runtime. But I can't seem to get the current Location of the mouse... Eh? There is no Location for Mouse? :(

推荐答案

在鼠标事件,您可以使用e.GetPosition来获得当前鼠标的位置,此功能可提供鼠标相对于特定元素的位置,也可以直接传递null。

In the Mouse event you can use e.GetPosition to get the current mouse position. This function can provide the mouse position relative to a specific element or you can just pass null.

下面是一个很简单的例子,没有命中测试或任何东西,只是一个按钮,你可以拖动。我用一个画布,以保持它短,但你可能会做更好的使用转换和转换控制到所需位置。

Here is a very simple example, no hit testing or anything, just a button that you can drag around. And I used a canvas to keep it short, but you would probably do better to use a transform and translate the control to the desired position.

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

这篇关于在运行时拖动表格控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆