近日,项目中有用到拖动排序的功能,一时没有思路,问了N个朋友,终于在一个朋友的帮助下搞定了这个排序。代码很简单也没加注释,自己看吧。
创建一个组件类(项目上右键->添加->组件),用户控件神马的都行
这里以一个Label为例
代码正文:
using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Windows.Forms; namespace WindowsFormsApplication1 { public partial class DragabledLabel : Label { private Point mouse_offse; private bool bDraged = false; private int xPos; public DragabledLabel() { InitializeComponent(); } public DragabledLabel(IContainer container) { container.Add(this); InitializeComponent(); } protected override void OnMouseDown(MouseEventArgs e) { bDraged = true; this.BringToFront(); this.BackColor = Color.Beige; xPos = this.Location.X; mouse_offse = new Point(-e.X, -e.Y); //base.OnMouseDown(e); } protected override void OnMouseMove(MouseEventArgs e) { if (bDraged) { Point mousePos = Control.MousePosition; mousePos.Offset(mouse_offse.X, mouse_offse.Y); this.Location = this.Parent.PointToClient(mousePos); } //base.OnMouseMove(e); } protected override void OnMouseUp(MouseEventArgs e) { if (e.Button == System.Windows.Forms.MouseButtons.Left) { Point mousePos = Control.MousePosition; mousePos.Offset(mouse_offse.X, mouse_offse.Y); this.Location = this.Parent.PointToClient(mousePos); this.BackColor = SystemColors.Control; bDraged = false; } Sort(); //base.OnMouseUp(e); } private void Sort() { ControlCollection DragabledLabels = this.Parent.Controls; Control parent = this.Parent; List<Control> list = new List<Control>(); while (DragabledLabels.Count > 0) { list.Add(GetMinYControl(DragabledLabels)); } for (int index = 0; index < list.Count; index++) { list[index].Location = new Point(0, 20 * index); parent.Controls.Add(list[index]); } } private Control GetMinYControl(ControlCollection cc) { Control c = cc[0]; if (cc.Count == 1) { cc.Remove(c); return c; } for (int i = 1; i < cc.Count; i++) { if (cc[i].Location.Y < c.Location.Y) { c = cc[i]; } } cc.Remove(c); return c; } } }
嗯,完成。在工具箱里找到这个组件,拖到窗体中就可以用
见附件:Winform拖动排序Demo
感謝您提供這麼棒的sample
想請教您,如果希望在 MouseUp前 就進行排序,就是拖動時就進行排序,
而不是拖動完成才進行排序,應該怎麼改程式呢?
@小慧:你可以試著在MouseMove的時候改一下試試
拿走,正好用到,但是如何实现拖动过程中就进行排序呢?楼主大银.
@x:看代码吧