简体   繁体   English

计时器为零后重新启用按钮

[英]Re-enabled the button after timer is zero

Need your help with the button.需要您的按钮帮助。 Its not re-enabling after the timer goes to zero.定时器归零后,它不会重新启用。 Though, it gets re-enabled after I clicked the UI or button and timer is zero.但是,在我单击 UI 或按钮并且计时器为零后,它会重新启用。 Any ideas?有任何想法吗? Thanks.谢谢。

Here's the command:这是命令:

        RelayCommand _testCommand;
        public ICommand TestCommand
        {
            get
            {
                if (_testCommand == null)
                {
                    _testCommand = new RelayCommand(
                        (object o) =>
                        {
                            IsEnabled = false;
                            StartTimer(5);
                        }, (object j)=> IsEnabled );
                }
                return _testCommand;
            }
            set { _testCommand = null; }
        }

Here's the property:这是财产:

    bool _isEnabled = true;
    bool IsEnabled
    {
        get { return _isEnabled; }
        set
        {
            _isEnabled = value;
            OnPropertyChanged();

        }
    }

Methods:方法:

    private Timer timer1;
    private int counter;
    private void StartTimer(int cnt)
    {
        counter = cnt;
        timer1 = new Timer();
        timer1.Elapsed += OnTimedEvent;
        timer1.Interval = 1000;
        timer1.Start();
    }

    private void OnTimedEvent(object sender, ElapsedEventArgs e)
    {
        Console.WriteLine(counter);
        counter--;
        if (counter < 0)
        {
            timer1.Stop();
            IsEnabled = true;
        }            
    }

Okay.好的。 I think I answered my own question.我想我回答了我自己的问题。 Correct me if I'm wrong but there are two things that are happening.如果我错了,请纠正我,但有两件事正在发生。 One is the ElapsedEventArgs is executing in the different thread.一种是 ElapsedEventArgs 在不同的线程中执行。 Two is the button (UI) is not updated automatically.二是按钮(UI)不会自动更新。 I have to call CommandManager.InvalidateRequerySuggested();我必须调用CommandManager.InvalidateRequerySuggested(); to force an update.强制更新。 Updated the OnTimedEvent method to:OnTimedEvent方法更新为:

    private void OnTimedEvent(object sender, ElapsedEventArgs e)
    {
        Console.WriteLine(Thread.CurrentThread.ManagedThreadId + " " + counter);
        counter--;
        if (counter < 0)
        {
            Application.Current.Dispatcher.Invoke(() =>
            {
                IsEnabled = true;
                timer1.Stop();
                CommandManager.InvalidateRequerySuggested();
                Console.WriteLine("The caller id now is " + Thread.CurrentThread.ManagedThreadId);
            });
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM