为什么不工作:RelayCommand RaiseCanExecuteChanged

时间:2012-10-13 19:38:34

标签: mvvm-light relaycommand

当我在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


}
}

提前谢谢

1 个答案:

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