WPF中使用鼠标拖放控件的网格控件

3
如何使用鼠标在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>

我需要将控制权从第一行转移到第二行,用鼠标可以吗?我需要拖放图片控件。


这个页面(https://dev59.com/4YLba4cB1Zd3GeqPeXDz)中有你问题的解决方案。 - Mohammad Bigdeli
1个回答

0

查看答案 感谢 @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;
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接