ICommand CanExecuteChanged not updating

前端 未结 2 789
慢半拍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:16

    You must have in your ICommand implementation some method like RiseCanExecuteChanged that fires the event CanExecuteChanged. Then every time that the selected item in the list changed, in your view model you execute the RaiseCanExecuteChanged from the command you want. Any way I suggest you to use any generic command, like the RelayCommand of GalaSoft MVVMLite library, or any implementation of DelegateCommand. Hope this helps...

    0 讨论(0)
  • 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!

    0 讨论(0)
提交回复
热议问题