当我在PressCommand.RaiseCanExecuteChanged();
方法中调用TimerOnElapsed
时,没有任何反应。
可能是什么问题? (GalaSoft.MvvmLight.WPF4 v4.0.30319和GalaSoft.MvvmLight.Extras.WPF4 v4.0.30319)
这是我的测试代码:
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
}
}
提前谢谢
答案 0 :(得分:6)
说明:
TimerOnElapsed
方法在工作线程上运行,但调用PressCommand.RaiseCanExecuteChanged();
必须在UI线程上。
所以这是解决方案,更新的TimerOnElapsed
方法:
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);
}