C#多选扩展模式下的listbox选择和取消选择项目

3

当我在列表框中单击未选择的项目时,它将被选中。客户希望如果再次单击(不使用cntrl键),则取消选择。

但是我尝试了很多方法但都没有成功。所以这是否可能,并且如果可能,有人可以用一些C#代码来解释一下吗?


这是一个Windows应用程序还是ASP.Net应用程序? - PCasagrande
1
你考虑过使用MultiSimple模式吗?http://stackoverflow.com/questions/11350514/winforms-listbox-append-selection/11350601#11350601 - Gonzalo.-
我没有使用MultiSimple,因为我认为它没有我想要的行为(就是这么简单)。但这正是我想要的,谢谢。 - Remco
4个回答

3

使用内置选项没有简单的方法来完成这个任务。我的解决方案是:当鼠标悬停在控件上时,以编程方式发送虚拟的Ctrl键按下事件(这样用户不需要按下任何键或思考什么)。如果您不需要MultiExtended的其他功能,请尝试使用MultiSimple (MSDN)。

如果你需要它,这里是一个丑陋的解决方案:

    [DllImport("user32.dll", SetLastError = true)]
    static extern void keybd_event(byte bVk, byte bScan, int dwFlags, int dwExtraInfo);

    public const byte KEYEVENTF_KEYUP = 0x02;
    public const int VK_CONTROL = 0x11;

    private void listBox1_MouseEnter(object sender, EventArgs e)
    {
        keybd_event(VK_CONTROL, (byte)0, 0, 0);
    }

    private void listBox1_MouseLeave(object sender, EventArgs e)
    {
        keybd_event(VK_CONTROL, (byte)0, KEYEVENTF_KEYUP, 0);
    }

以下是我在这里的回答。


@NominSim 你不需要按Ctrl键。可以通过程序自动执行虚拟按键。 - Matt Razza
1
哦,现在我明白了,你说得对,虽然有点丑,但是还是+1。 - NominSim
这个回答值得两个赞。好的,你回答了两次,所以你得到了两个赞! - Cyril Gandon

1
您可以在所选索引事件中添加一些内容,如果所选索引与先前选择的相同(将其存储在某个地方),则将所选索引设置为-1,这样就不会选择任何内容。

0

遵循 SelectedValueChanged 事件并添加以下内容:

string selected = null;

private void listBox1_SelectedValueChanged(object sender, EventArgs e)
{
    ListBox lb = sender as ListBox;
    if (lb == null) { return; }
    if (lb.SelectedItem != null && lb.SelectedItem.ToString() == selected)
    {
        selected = lb.SelectedItem.ToString();
        lb.SetSelected(lb.SelectedIndex, false);
    }
    else 
    {
        selected = lb.SelectedItem == null ? null : lb.SelectedItem.ToString();
    }
}

0
当您单击 ListBox 的空白区域时,此代码将取消选择所有/特定的 ListBox 项目。
        private void listBox1_MouseClick(object sender, MouseEventArgs e)
        {
            int totalHeight = listBox1.ItemHeight * listBox1.Items.Count;

            if(e.Y < totalHeight && e.Y >= 0)
            {
                // Item is Selected which user clicked.

                if(listBox1.SelectedIndex == 0 && listBox1.SelectedItem != null) // Check if Selected Item is NOT NULL.
                {
                    MessageBox.Show("Selected Index : " + listBox1.SelectedItem.ToString().Trim());
                }
                else
                {
                    listBox1.SelectedIndex = -1;
                    MessageBox.Show("Selected Index : No Items Found");
                }
            }
            else
            {
                // All items are Unselected.
                listBox1.SelectedIndex = -1;
                MessageBox.Show("Selected Index : " + listBox1.SelectedItem); // Do NOT use 'listBox1.SelectedItem.ToString().Trim()' here.
            }
        }

同时,当项目被选中/取消选中时,您也可以更改代码以实现您想要的功能。
如果您有任何问题,请留下评论。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接