版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/mill_li/article/details/91412475
前面我们已经介绍了CheckedListBox,ListBox和它其实差不多,这里我们实现个拖拽的小功能,来学习ListBox控件
1.界面布局
界面布局这里很简单,就是一个ListBox
我们在代码里面为它添加元素,并重新事件来实现拖拽的功能
2.用法示例
想要实现拖拽功能,这里我们必须重新OnMouseDown,OnDragOver,OnDragDrop这三个事件,并且将AllowDrop属性设置为True,下面我们来看代码
using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Drawing.Drawing2D; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace WindowsFormsApplication1 { public partial class FormMain : Form { public FormMain(ArrayList arrip_list) { InitializeComponent(); listBox1.Items.Add("先天五态"); listBox1.Items.Add("太易"); listBox1.Items.Add("太初"); listBox1.Items.Add("太始"); listBox1.Items.Add("太素"); listBox1.Items.Add("太极"); } } class MListBox : ListBox { //拖放操作 //鼠标按下 protected override void OnMouseDown(MouseEventArgs e) { base.OnMouseDown(e); if (SelectedItem != null) { DoDragDrop(SelectedItem, DragDropEffects.Move); } //Console.WriteLine("OnMouseDown\n"); } //鼠标拖动 protected override void OnDragOver(DragEventArgs e) { base.OnDragOver(e); e.Effect = DragDropEffects.Move; //Console.WriteLine("OnDragOver\n"); } //鼠标松开 protected override void OnDragDrop(DragEventArgs e) { base.OnDragDrop(e); Point point = PointToClient(new Point(e.X, e.Y)); int index = IndexFromPoint(point); string sourceItemText = GetItemText(Items[SelectedIndex]); Items.Remove(sourceItemText); Items.Insert(index, sourceItemText); //选中当前选项 SelectedIndex = index; //Console.WriteLine("OnDragDrop\n"); } //拖放操作结束 } }
代码其实很简单,就是在鼠标松开的时候判断当前位置在哪一项,然后将拖拽的项重新插入到该项后面即可
文章来源: https://blog.csdn.net/mill_li/article/details/91412475