C# winform ListBox 按项目取消选择

问题描述 投票:0回答:1

我在点击取消时遇到问题

using System.Windows.Forms;

namespace WindowsFormsApp2
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

            lbItems.Items.Add("1");
            lbItems.Items.Add("2");
            lbItems.Items.Add("3");
            lbItems.Items.Add("4");
            lbItems.Items.Add("5");
            lbItems.Items.Add("6");

            lbItems.MouseDown += LbItems_MouseDown;
            lbItems.SelectedValueChanging // not found
        }

        private void LbItems_MouseDown(object sender, MouseEventArgs e)
        {
          // I want to cancel click to the item in ListBox
        }
    }
}

我以为有一个

SelectedValueChanging
事件可以让你取消对某个元素的选择并保留在旧的元素上。也许用 DevEXpress 中的另一个控件替换
ListBox
?但哪一个呢?

c# winforms listbox devexpress
1个回答
0
投票

使用第三方控件的替代方法是创建自己的扩展

ListBoxEx
类来实现
SelectedIndexChanging
(确保在设计器中将其交换出来。)

class ListBoxEx : ListBox
{
    private const int WM_LBUTTONDOWN = 0x0201;
    protected override void WndProc(ref Message m)
    {
        if (m.Msg == WM_LBUTTONDOWN)
        {
            var e = new SelectedValueChangingEventArgs(IndexFromPoint(new Point((int)m.LParam & 0xFFFF, (int)m.LParam >> 16)));
            SelectedValueChanging?.Invoke(this, e);
            if (e.Cancel) return;
        }
        base.WndProc(ref m);
    }

    public event EventHandler<SelectedValueChangingEventArgs>? SelectedValueChanging;
}

class SelectedValueChangingEventArgs : CancelEventArgs
{
    public SelectedValueChangingEventArgs(int index) => Index = index;
    public int Index { get; }
}

这是一个能够以编程方式选择项目的最小示例(即通过使用

NumericUpDownControl
间接进行选择),同时不允许鼠标选择。这可能不是“完全”您想要实现的目标,但重点是简单地演示如何控制鼠标事件是否导致选择。

minimal example

public partial class MainForm : Form
{
    public MainForm()
    {
        InitializeComponent();
        lbItems.Items.Add("1");
        lbItems.Items.Add("2");
        lbItems.Items.Add("3");
        lbItems.Items.Add("4");
        lbItems.Items.Add("5");
        lbItems.Items.Add("6");

        lbItems.SelectedValueChanging += LbItems_SelectedValueChanging;
        numericUpDown.ValueChanged += NumericUpDown_ValueChanged;
    }
    private void LbItems_SelectedValueChanging(object? sender, SelectedValueChangingEventArgs e)
    {
        e.Cancel = !_allowChange;
    }
    private void NumericUpDown_ValueChanged(object? sender, EventArgs e)
    {
        lbItems.SelectedIndex = lbItems.FindStringExact(numericUpDown.Value.ToString());
    }
    bool _allowChange = false; // Set true to allow mouse selection under certain conditions.
}
© www.soinside.com 2019 - 2024. All rights reserved.