拖放形状

Iva*_*van 3 c# wpf

我在stackpanel中有一个矩形形状,我想使用WPF拖放到网格中的鼠标!如果有人可以帮助我,我很感激吗?谢谢大家.

Ed *_* S. 8

一个非常简单的实现如下.它只是处理鼠标按钮向下/向上/移动事件,Rectangle以便与鼠标移动一起定位.没有错误检查,也没有阻止用户将矩形拖离Canvas并将其留在那里.

XAML:


<Window x:Class="WpfApplication6.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">
    <Grid>
        <Canvas Name="canvas">
            <Rectangle
                Name="rect"
                Width="50"
                Height="50"
                Canvas.Left="0"
                Canvas.Top="0"
                Fill="Red"
                MouseLeftButtonDown="rect_MouseLeftButtonDown"
                MouseLeftButtonUp="rect_MouseLeftButtonUp"
                MouseMove="rect_MouseMove"
                />
        </Canvas>
    </Grid>
</Window>
Run Code Online (Sandbox Code Playgroud)

代码背后:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace WpfApplication6
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private bool _isRectDragInProg;

        public MainWindow()
        {
            InitializeComponent();
        }

        private void rect_MouseLeftButtonDown( object sender, MouseButtonEventArgs e )
        {
            _isRectDragInProg = true;
            rect.CaptureMouse();
        }

        private void rect_MouseLeftButtonUp( object sender, MouseButtonEventArgs e )
        {
            _isRectDragInProg = false;
            rect.ReleaseMouseCapture();
        }

        private void rect_MouseMove( object sender, MouseEventArgs e )
        {
            if( !_isRectDragInProg ) return;

            // get the position of the mouse relative to the Canvas
            var mousePos = e.GetPosition(canvas);

            // center the rect on the mouse
            double left = mousePos.X - (rect.ActualWidth / 2);
            double top = mousePos.Y - (rect.ActualHeight / 2);
            Canvas.SetLeft( rect, left );
            Canvas.SetTop( rect, top );
        }
    }
}
Run Code Online (Sandbox Code Playgroud)