简体   繁体   中英

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. 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. Two is the button (UI) is not updated automatically. I have to call CommandManager.InvalidateRequerySuggested(); to force an update. Updated the OnTimedEvent method to:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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