Skip to main content
 首页 » 编程设计

c#之防止事件从一次操作中多次触发

2024年02月24日13shanyou

如何防止由单个操作触发多个同类事件?

例如,我有一个包含一些项目的ListView。当我选择或取消选择所有项目时,SelectedIndexChanged 事件会为每个项目触发一次。相反,我希望接收单个事件指示用户的操作(选择/取消选择项目),而不管项目的数量。

有什么办法可以实现吗?

请您参考如下方法:

您不能更改 ListView 代码,并且子类化它不会提供很多选项。

我建议您只需在您的代码中添加一个小的延迟(200 毫秒或类似时间)——即您只在上次更新后的一段时间内进行计算。像这样的东西:

using System; 
using System.Windows.Forms; 
static class Program { 
    [STAThread] 
    static void Main() { 
        Application.EnableVisualStyles(); 
        ListView list; 
        TextBox txt; 
        Timer tmr = new Timer(); 
        tmr.Interval = 200; 
        Form form = new Form { 
            Controls = { 
                (txt = new TextBox { Dock = DockStyle.Fill, Multiline = true}), 
                (list = new ListView { Dock = DockStyle.Right, View = View.List, 
                   Items = { "abc", "def" , "ghi", "jkl", "mno" , "pqr"}}) 
            } 
        }; 
        list.SelectedIndexChanged += delegate { 
            tmr.Stop(); 
            tmr.Start(); 
        }; 
        tmr.Tick += delegate { 
            tmr.Stop(); 
            txt.Text += "do work on " + list.SelectedItems.Count + " items" 
                 + Environment.NewLine; 
        }; 
        Application.Run(form); 
    } 
}