問題描述
我剛剛開始使用 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();
}
}
}
}
這篇關于運行時在窗體上拖動控件的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!