I'm implementing the CommunityToolkit.Mvvm framework on my WPF desktop application. I'm using the in-built RelayCommand with the 'CanExecute' coming from a navigation service helper class that I've written elsewhere.
Very simply I want the Button which is bound to the RelayCommand to update the CanExecute boolean when the navigation service is used to switch between views. On trying to raise the Command.NotifyCanExecuteChanged();
method, I am getting a System.StackOverflowException
on loading the view?
public MainViewModel() {
_navigationServices = new NavigationServices();
this.PreviousViewCommand = new RelayCommand(this.PreviousViewModel, CanNavigate);
}
private void PreviousViewModel() {
this.CurrentPageViewModel = _navigationServices.GetPreviousView();
}
private bool CanNavigate() {
this.PreviousViewCommand.NotifyCanExecuteChanged(); /// it is here where the StackOverflow Exception is being thrown
return _navigationService.CanNavigate;
}
Navigation in WPF MVVM is a bit of a pain, but this seems like an easy piece of data binding between a button, command and the CanExecute
. Can someone help me in finding what I'm missing?
CodePudding user response:
What calling NotifyCanExecuteChanged
does is telling every control that is bound to the command to call the CanExecute
method of the command... which in this case then calls its NotifyCanExecuteChanged
method, which calls the CanExecute
method and so on, which is why you get the StackOverflowException
.
I want the Button which is bound to the RelayCommand to update the CanExecute boolean when the navigation service is used to switch between views
I believe what you want to achieve can be done by simply calling this.PreviousViewCommand.NotifyCanExecuteChanged()
whenever the views have been switched. That should suffice; either way, don't call the NotifyCanExecuteChanged
method of a command in its own CanExecute
method.