wpf-控件随鼠标移动

2023-12-13 09:37:28

主要通过三个鼠标事件实现:

事件PreviewMouseDown:鼠标按下触发
事件PreviewMouseMove:鼠标移动触发
事件PreviewMouseUp?:鼠标松开触发

示例代码:

        <Button Width="50"
                Height="40"
                Background="LightBlue"
                Content="Move" HorizontalAlignment="Left" VerticalAlignment="Top"
                PreviewMouseDown="Button_PreviewMouseDown"
                PreviewMouseMove="Button_PreviewMouseMove"
                PreviewMouseUp="Button_PreviewMouseUp" />

RenderTransform:元素呈现位置的转换信息?

        public bool isMouseDown = false;
        public Point mouseDownPosition;
        public Point mouseDownControlPosition;
        private void Button_PreviewMouseDown(object sender, MouseButtonEventArgs e)
        {
            isMouseDown = true;
            mouseDownPosition = e.GetPosition(this);
            var ctl = sender as UIElement;
            var transform = ctl.RenderTransform as TranslateTransform;
            if (transform == null)
            {
                transform = new TranslateTransform();
                ctl.RenderTransform = transform;
            }
            mouseDownControlPosition = new Point(transform.X, transform.Y);
            ctl.CaptureMouse();
        }

        private void Button_PreviewMouseMove(object sender, MouseEventArgs e)
        {
            if (isMouseDown)
            {
                var ctl = sender as UIElement;
                var pos = e.GetPosition(this);
                var dp = pos - mouseDownControlPosition;
                var translate = ctl.RenderTransform as TranslateTransform;
                translate.X = mouseDownControlPosition.X + dp.X;
                translate.Y = mouseDownControlPosition.Y + dp.Y;
            }
        }

        private void Button_PreviewMouseUp(object sender, MouseButtonEventArgs e)
        {
            var ctl = sender as UIElement;
            isMouseDown = false;
            ctl.ReleaseMouseCapture();
        }

文章来源:https://blog.csdn.net/rwo_bear/article/details/134963178
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。