Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

StackOverflow Exception when notifying RelayCommand of CanExecuteChanged using CommunityToolkit.Mvvm

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading