Why not working: RelayCommand RaiseCanExecuteChanged
-
07-07-2021 - |
質問
When I call the PressCommand.RaiseCanExecuteChanged();
in the TimerOnElapsed
method, nothing happened.
What could be the problem? (GalaSoft.MvvmLight.WPF4 v4.0.30319 and GalaSoft.MvvmLight.Extras.WPF4 v4.0.30319)
Here is my test code:
using System.Timers;
using System.Windows;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
namespace CommandTest {
public class MainWindowVM : ViewModelBase {
public MainWindowVM() {
PressCommand = new RelayCommand(
() => MessageBox.Show("Pressed"),
() => _canExecute);
PressCommand.CanExecuteChanged += (sender, args) => System.Diagnostics.Debug.WriteLine(System.DateTime.Now.ToLongTimeString() + " CanExecuteChanged");
_timer = new Timer(1000);
_timer.Elapsed += TimerOnElapsed;
_timer.Enabled = true;
}
public RelayCommand PressCommand { get; private set; }
#region Private
private void TimerOnElapsed(object sender, ElapsedEventArgs elapsedEventArgs) {
_canExecute = !_canExecute;
PressCommand.RaiseCanExecuteChanged();
System.Diagnostics.Debug.WriteLine("At {0} enabled: {1}", elapsedEventArgs.SignalTime.ToLongTimeString(), _canExecute);
}
private readonly Timer _timer;
private bool _canExecute;
#endregion
}
}
Thank you in advance
解決
Explanation:
The TimerOnElapsed
method runs on a Worker Thread but to invoke the PressCommand.RaiseCanExecuteChanged();
must be on the UI thread.
So this is the solution, the updated TimerOnElapsed
method:
private void TimerOnElapsed(object sender, ElapsedEventArgs elapsedEventArgs) {
_canExecute = !_canExecute;
Application.Current.Dispatcher.Invoke(PressCommand.RaiseCanExecuteChanged);
System.Diagnostics.Debug.WriteLine("At {0} enabled: {1}", elapsedEventArgs.SignalTime.ToLongTimeString(), _canExecute);
}
所属していません StackOverflow