gpt4 book ai didi

wpf - 用鼠标在网格 wpf 中拖放控件

转载 作者:行者123 更新时间:2023-12-05 08:00:17 35 4
gpt4 key购买 nike

如何用鼠标在 grid wpf 中拖放控件?

<Window x:Class="Animation_Move.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" >
<Grid>
<Grid Name="Grm" Width="500" Height="500" Background="#FF14831E">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="100"/>
<ColumnDefinition Width="100"/>
<ColumnDefinition Width="100"/>
<ColumnDefinition Width="100"/>
<ColumnDefinition Width="100"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="100"/>
<RowDefinition Height="100"/>
<RowDefinition Height="100"/>
<RowDefinition Height="100"/>
<RowDefinition Height="100"/>
</Grid.RowDefinitions>
<Image Name="Soldier" Grid.Row="1" Grid.Column="1" Source="Soldier-Red.png" Width="26" Height="34" ></Image>
</Grid>

</Grid>

我需要将控件从第一行移到第二行。这可以用鼠标实现吗?我需要拖放图像控件。

最佳答案

View the answer非常感谢@Mediator

 Point _anchorPoint;
Point _currentPoint;
bool _isInDrag;

private void root_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
var element = sender as FrameworkElement;
_anchorPoint = e.GetPosition(null);
if (element != null) element.CaptureMouse();
_isInDrag = true;
e.Handled = true;
}

private readonly TranslateTransform _transform = new TranslateTransform();
private void root_MouseMove(object sender, MouseEventArgs e)
{
if (!_isInDrag) return;
_currentPoint = e.GetPosition(null);

_transform.X += _currentPoint.X - _anchorPoint.X;
_transform.Y += (_currentPoint.Y - _anchorPoint.Y);
RenderTransform = _transform;
_anchorPoint = _currentPoint;
}

private void root_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
if (!_isInDrag) return;
var element = sender as FrameworkElement;
if (element != null) element.ReleaseMouseCapture();
_isInDrag = false;
e.Handled = true;
}

关于wpf - 用鼠标在网格 wpf 中拖放控件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18424770/

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