2012-10-13 34 views
2

當我撥打TimerOnElapsed方法中的PressCommand.RaiseCanExecuteChanged();時,什麼都沒有發生。爲什麼不工作:RelayCommand RaiseCanExecuteChanged

可能是什麼問題? (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 


} 
} 

預先感謝您

回答

6

說明:

TimerOnElapsed方法在Worker線程上運行,但調用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); 
    } 
+0

謝謝你救了我很多時間。 – Jsinh