gpt4 book ai didi

c# - WPF 用鼠标移动元素

转载 作者:行者123 更新时间:2023-12-05 08:15:27 26 4
gpt4 key购买 nike

我正在尝试在 WPF 应用程序中使用鼠标移动按钮。

XAML Grid 是结构的根:

<Grid Name="MyGrid"            >
<Button Name="Samplebutton"
PreviewMouseDown="Samplebutton_PreviewMouseDown"
PreviewMouseUp="Samplebutton_PreviewMouseUp"
PreviewMouseMove="Samplebutton_PreviewMouseMove"
Content="Moving" Width="100" Height="35"/>
</Grid>

和代码背后:

private bool _isMoving;


private void Samplebutton_PreviewMouseDown(object sender, MouseButtonEventArgs e)
{
_isMoving = true;
}

private void Samplebutton_PreviewMouseUp(object sender, MouseButtonEventArgs e)
{
_isMoving = false;
}

private void Samplebutton_PreviewMouseMove(object sender, MouseEventArgs e)
{
if (!_isMoving) return;

TranslateTransform transform = new TranslateTransform();
transform.X = Mouse.GetPosition(MyGrid).X;
transform.Y = Mouse.GetPosition(MyGrid).Y;
this.Samplebutton.RenderTransform = transform;
}

首先点击按钮将他移远,然后我可以移动按钮,但第一次按钮被移开。我缺少什么?

最佳答案

以下是您问题的完整解决方案:

private bool _isMoving;
private Point? _buttonPosition;
private double deltaX;
private double deltaY;
private TranslateTransform _currentTT;

private void Samplebutton_PreviewMouseDown(object sender, MouseButtonEventArgs e)
{
if(_buttonPosition == null)
_buttonPosition = Samplebutton.TransformToAncestor(MyGrid).Transform(new Point(0, 0));
var mousePosition = Mouse.GetPosition(MyGrid);
deltaX = mousePosition.X - _buttonPosition.Value.X;
deltaY = mousePosition.Y - _buttonPosition.Value.Y;
_isMoving = true;
}

private void Samplebutton_PreviewMouseUp(object sender, MouseButtonEventArgs e)
{
_currentTT = Samplebutton.RenderTransform as TranslateTransform;
_isMoving = false;
}

private void Samplebutton_PreviewMouseMove(object sender, MouseEventArgs e)
{
if (!_isMoving) return;

var mousePoint = Mouse.GetPosition(MyGrid);

var offsetX = (_currentTT == null ?_buttonPosition.Value.X : _buttonPosition.Value.X - _currentTT.X) + deltaX - mousePoint.X;
var offsetY = (_currentTT == null ? _buttonPosition.Value.Y : _buttonPosition.Value.Y - _currentTT.Y) + deltaY - mousePoint.Y;

this.Samplebutton.RenderTransform = new TranslateTransform(-offsetX, -offsetY);
}

关于c# - WPF 用鼠标移动元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46380682/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com