WPF Canvas mouse move event implement drag function

复制代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
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 WpfApp301
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {

        private Canvas cvs { get; set; }
        private Ellipse elp { get; set; }
        private bool isMoving { get; set; }
        private Point currentPt { get; set; }

        private int elpWidth = 200;
        private int elpHeight = 100;
        private int offSetX { get; set; }
        private int offSetY { get; set; }

        public MainWindow()
        {
            InitializeComponent();
            InitData();            
        }

        private void InitData()
        {
            cvs = new Canvas();
            elp = new Ellipse();
            elp.Width = elpWidth;
            elp.Height = elpHeight;
            offSetX = elpWidth / 2;
            offSetY = elpHeight / 2;
            elp.Fill = new SolidColorBrush(Colors.Blue);
            Canvas.SetLeft(elp, 0);
            Canvas.SetTop(elp, 0);
            if (!cvs.Children.Contains(elp))
            {
                cvs.Children.Add(elp);
            }
            this.Content = cvs;
        }

        private void Window_MouseDown(object sender, MouseButtonEventArgs e)
        {
            currentPt=e.GetPosition(this);
        }

        private void Window_MouseMove(object sender, MouseEventArgs e)
        {
            if(e.LeftButton==MouseButtonState.Pressed)
            {
                isMoving = true;
            } 
        }

        private void Window_MouseUp(object sender, MouseButtonEventArgs e)
        {
            if (e.ButtonState == MouseButtonState.Released && e.ChangedButton == MouseButton.Left && isMoving)
            {
                var pt = e.GetPosition(this);
                Canvas.SetLeft(elp,(int)pt.X-offSetX);
                Canvas.SetTop(elp, (int)pt.Y-offSetY);
                this.Title = $"{e.GetPosition(this).X},{e.GetPosition(this).Y}";
            }
        }
    }
}
复制代码

 

 

 

 

 

 

 

 

 

posted @   FredGrit  阅读(7)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现
历史上的今天:
2019-08-28 convert datatable to List<T>
2019-08-28 ExcelHelper based on NPOI
点击右上角即可分享
微信分享提示