如何防止由单个操作触发多个同类事件?
例如,我有一个包含一些项目的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);
}
}
