防止单个动作多次触发事件 [英] Prevent events from firing multiple times from single action

查看:55
本文介绍了防止单个动作多次触发事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何防止一次操作触发多个同类事件?

How can I prevent the firing of multiple events of the same kind triggered by a single action?

例如,我有一个包含某些项目的 ListView .当我选择或取消选择所有项目时,每个项目都会触发一次 SelectedIndexChanged 事件.相反,我希望收到一个事件事件指示用户的操作(项目的选择/取消选择),而与项目的数量无关.

For example, I have a ListView containing some items. When I select or deselect all items, the SelectedIndexChanged event is fired once for each item. Rather, I would like to receive a single event indication the user's action (selection/deselection of items), regardless of the number of items.

有什么办法可以做到这一点?

Is there any way to achieve this?

推荐答案

您不能更改 ListView 代码,并且对其进行子类化并不能提供很多选择.

You can't change the ListView code, and subclassing it doesn't provide many options.

我建议您在代码中添加一个小的延迟(200毫秒或类似时间)-即,您只在最后一次更新后进行一小段时间的计算.像这样:

I would suggest that you simply add a small delay (200ms or similar) to your code - i.e. you only do the calculation a little while after the last update. Something like:

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);
    }
}

这篇关于防止单个动作多次触发事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆