【问题标题】:Why not working: RelayCommand RaiseCanExecuteChanged为什么不工作:RelayCommand RaiseCanExecuteChanged
【发布时间】:2012-10-13 19:38:33
【问题描述】:

当我在TimerOnElapsed 方法中调用PressCommand.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


}
}

提前谢谢你

【问题讨论】:

    标签: mvvm-light relaycommand


    【解决方案1】:

    解释:

    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-08-15
    • 2011-10-19
    • 2018-06-21
    • 2014-04-12
    • 2011-12-13
    • 2018-02-23
    • 1970-01-01
    • 2016-11-19
    • 1970-01-01
    相关资源
    最近更新 更多