取消ListBox SelectedIndexChange事件

Jos*_*osh 14 c# events listbox winforms

是否可以取消winforms应用程序上列表框的SelectedIndexChange事件?这似乎是合乎逻辑的事情,我必须忽略一些简单的功能.基本上,我一直在弹出一个消息框,询问用户是否真的想要移动到另一个项目,因为这将改变UI,我不希望他们的更改丢失.如果用户没有保存他们正在处理的内容,我希望能够取消该活动.有没有更好的方法呢?

Osk*_*lin 17

你无法取消它.

我几天前所做的就是拥有一个带有最新选定索引的变量.然后,当事件触发时,您询问用户是否要保存,这是在事件处理程序中完成的.如果用户选择"取消",则再次更改ID.

问题是,这将使事件再次发生.所以我使用的是一个bool只是说"抑制".在事件处理程序的顶部,我有:

if(Inhibit)
   return;
Run Code Online (Sandbox Code Playgroud)

然后在这下面你提出问题,你做这样的事情:

DialogResult result = MessageBox.Show("yadadadad", yadada cancel etc);
if(result == DialogResult.Cancel){
   Inhibit = true; //Make sure that the event does not fire again
   list.SelectedIndex = LastSelectedIndex; //your variable
   Inhibit = false; //Enable the event again
}
LastSelectedIndex = list.SelectedIndex; // Save latest index.
Run Code Online (Sandbox Code Playgroud)

  • 在阅读此答案后,我发现了一个细微的变化 - 您可以删除事件处理程序而不是使用禁止标志:`list.SelectedIndexChanged -= list_SelectedIndexChanged; 列表.SelectedIndex = LastSelectedIndex; list.SelectedIndexChanged += list_SelectedIndexChanged;` 可能有一些原因表明这是一种较差的方法,但对于我的目的来说效果很好。 (2认同)

naw*_*fal 9

这正是@Oskar Kjellin的方法,但有一点扭曲.也就是说,一个较小的变量和一个选定的索引改变了事件,它真的表现得像一个选定的索引改变了事件.我经常想知道为什么即使我点击完全相同的选定项目,选择索引更改事件也会被触发.在这里它没有.是的,这是一个偏差,所以要更加确定你是否希望它在那里.

    int _selIndex = -1;
    private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (listBox1.SelectedIndex == _selIndex)
            return;

        if (MessageBox.Show("") == DialogResult.Cancel)
        {
            listBox1.SelectedIndex = _selIndex;
            return;
        }

        _selIndex = listBox1.SelectedIndex;
        // and the remaining part of the code, what needs to happen when selected index changed happens
    }
Run Code Online (Sandbox Code Playgroud)


小智 6

我刚遇到这个问题.我做的是当用户进行更改时,我设置ListBox.Enabled = false; 这不允许他们选择不同的索引.一旦他们保存或放弃他们的更改,我设置ListBox.Enabled = true; 可能不像提示那样光滑,但它完成了工作.


小智 5

更优雅,使用 Tag 属性:

        if ((int)comboBox.Tag == comboBox.SelectedIndex)
        {
            // Do Nothing
        }
        else
        {
            if (MessageBox.Show("") == DialogResult.Cancel)
            {
                comboBox.SelectedIndex = (int)comboBox.Tag;
            }
            else
            {
                // Reset the Tag
                comboBox.Tag = comboBox.SelectedIndex;

                // Do what you have to
            }
        }
Run Code Online (Sandbox Code Playgroud)