ICommand CanExecuteChanged not updating

前端 未结 2 792
慢半拍i
慢半拍i 2021-01-19 05:28

I am trying for MVVM pattern basic level and got struck at ICommand CanExecute changed. I have XAML binding as follows:

    

        
2条回答
  •  面向向阳花
    2021-01-19 06:31

    As Raul Otaño has pointed out, you can raise the CanExecuteChanged. However, not all MVVM frameworks provide a RaiseCanExecuteChanged method. It's also worth noting that the actual event CanExecuteChanged must be called on the UI thread. So, if you're expecting a callback from some thread in your model, you need to invoke it back to the UI thread, like this:

        public void RaiseCanExecuteChanged()
        {
            if (CanExecuteChanged != null)
            {
                Application.Current.Dispatcher.Invoke((Action)(() => { CanExecuteChanged(this, EventArgs.Empty); }));
            }
        }
    

    I would very much recommend against calling CommandManager.InvalidateRequerySuggested() because although this works functionally, and is ok for small applications, it is indiscriminate and will potentially re-query every command! In a large system with lots of commands, this can be very very slow!

提交回复
热议问题