I am trying for MVVM pattern basic level and got struck at ICommand CanExecute changed. I have XAML binding as follows:
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...
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!