2

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


}
}

先感谢您

4

1 回答 1

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);
    }
于 2012-10-18T14:29:42.323 回答