winform控件之ListBox

Windows Form控件:ListBox拖拽功能实现
本文介绍如何在Winform应用中为ListBox控件添加拖拽功能。通过重新定义OnMouseDown, OnDragOver, OnDragDrop事件并设置AllowDrop属性为True,可以实现元素的拖放操作。" 100785790,8504150,Python基础知识:数据类型、装饰器、迭代器与生成器,"['Python基础', '数据结构', '函数', '字符串操作']

前面我们已经介绍了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");
        }
        //拖放操作结束
 
    }
}


代码其实很简单,就是在鼠标松开的时候判断当前位置在哪一项,然后将拖拽的项重新插入到该项后面即可

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值