How to realize the drag of controls in Grid based on wpf of C #
这篇文章主要介绍"基于C#的wpf怎么实现Grid内控件拖动",在日常操作中,相信很多人在基于C#的wpf怎么实现Grid内控件拖动问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答"基于C#的wpf怎么实现Grid内控件拖动"的疑惑有所帮助!接下来,请跟着小编一起来学习吧!
前言:
有一些业务场景中我们需要拖动控件,在Grid中就可以实现控件拖动,通过设置Margin属性即可,根据鼠标的移动,设置相应的Margin的Left、Top,当然有时也不是直接设置的,需要根据HorizontalAlignment、VerticalAlignment值有不同的计算方法。
一、如何实现?1.注册鼠标事件
拖动的控件需要注册3个鼠标事件分别是,鼠标按下、鼠标移动、鼠标弹起。
以Button为例:
2.记录位置
在鼠标按下事件中记录位置。
//鼠标是否按下bool _isMouseDown = false;//鼠标按下的位置Point _mouseDownPosition;//鼠标按下控件的MarginThickness _mouseDownMargin;//鼠标按下事件private void Button_MouseDown(object sender, MouseButtonEventArgs e){ var c = sender as Control; _isMouseDown = true; _mouseDownPosition = e.GetPosition(this); _mouseDownMargin = c.Margin;}3.跟随鼠标移动
鼠标按下后移动鼠标,控件需要跟随鼠标移动。根据HorizontalAlignment、VerticalAlignment值不同,计算Margin的方式也不同。
private void Button_MouseMove(object sender, MouseEventArgs e){ if (_isMouseDown) { var c = sender as Control; var pos = e.GetPosition(this); var dp = pos - _mouseDownPosition; double left, top, right, bottom; if (c.HorizontalAlignment == HorizontalAlignment.Stretch|| c.HorizontalAlignment == HorizontalAlignment.Center) //中央移动距离是双倍 { left= _mouseDownMargin.Left+ dp.X * 2; right = _mouseDownMargin.Right; } else if(c.HorizontalAlignment== HorizontalAlignment.Left) //左边是正常距离 { left = _mouseDownMargin.Left + dp.X ; right = _mouseDownMargin.Right; } else //右边是右边距距离 { left = _mouseDownMargin.Left; right = _mouseDownMargin.Right - dp.X; } if (c.VerticalAlignment == VerticalAlignment.Stretch || c.VerticalAlignment == VerticalAlignment.Center) //中央移动距离是双倍 { top = _mouseDownMargin.Top+ dp.Y* 2; bottom = _mouseDownMargin.Bottom; } else if (c.VerticalAlignment == VerticalAlignment.Top) //顶部是正常距离 { top = _mouseDownMargin.Top + dp.Y ; bottom = _mouseDownMargin.Bottom; } else //底部是底边距距离 { top = _mouseDownMargin.Top ; bottom = _mouseDownMargin.Bottom- dp.Y; } c.Margin = new Thickness(left, top, right, bottom); }}4.恢复标识
鼠标弹起后需要恢复标识,让控件不再跟随鼠标移动。
private void Button_MouseUp(object sender, MouseButtonEventArgs e){ if (_isMouseDown) { _isMouseDown = false; //移动了的控件不响应点击事件(此处根据具体需求) e.Handled = true; }}二、示例
示例代码:
效果预览:
到此,关于"基于C#的wpf怎么实现Grid内控件拖动"的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注网站,小编会继续努力为大家带来更多实用的文章!