WPF防止事件连续多次响应

在处理一些交互事件的时候,很容易出现单击或双击,不小心触发了多次的问题。

目前没有找到很好的处理办法。于是想着自己封装一个类。

public class EventResponseController
{
    private static EventResponseController _instance;
    public static EventResponseController Instance => _instance ?? (_instance = new EventResponseController());

    private DateTime _lastTime = DateTime.MinValue;

    public bool CanExecute()
    {
        var now = DateTime.Now;
        if (now.Subtract(_lastTime) < TimeSpan.FromMilliseconds(800))
            return false;

        _lastTime = now;
        return true;
    }
}

执行代码,只需要在执行控制的事件方法前加上这么两行代码:

if (EventResponseController.Instance.CanExecute() == false)
    return;

//事件的执行代码

 

欢迎提供更好的办法。

posted @ 2022-08-03 12:47  wzwyc  阅读(251)  评论(0编辑  收藏  举报