使用鼠标在网格 wpf 中拖放控件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18424770/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 09:29:33 来源:igfitidea点击:
drag and drop control within grid wpf with mouse
提问by Sun Rise
how to drag and drop control within grid wpf with mouse ?
如何使用鼠标在网格 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>
I need to shift control from the first row to the second row.Is this possible with mouse? i need to drag and drop image control.
我需要将控制权从第一行转移到第二行。这可以用鼠标吗?我需要拖放图像控件。
回答by Sun Rise
View the answerthank a lot @Mediator
查看答案非常感谢@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;
}

