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 に答える