Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF Custom ICommand implementation and the CanExecuteChanged event

in my WPF UI, I use RoutedCommands that I refer to in my xaml via the following code:

Command="viewModel:MessageListViewModel.DeleteMessagesCommand"

I don't like this static link to my ViewModel class,I think this is not as nice as creating a custom ICommand implementation and use a syntax like the following

Command="{Binding DeleteMessagesCommand}"

Having created one, I notice one major drawback of what I've done: RoutedCommands utilize the CommandManager and (in some way that is completely opaque to me) fire the CommandManager.RequerySuggested event, so that their CanExecute Method is requeried automatically. As for my custom implementation, CanExecute is only fired once at startup and never again after that.

Does anybody have an elegant solution for this?

like image 569
Sebastian Edelmeier Avatar asked Sep 22 '10 10:09

Sebastian Edelmeier


1 Answers

Just implement the CanExecuteChanged event as follows:

public event EventHandler CanExecuteChanged
{
    add { CommandManager.RequerySuggested += value; }
    remove { CommandManager.RequerySuggested -= value; }
}

When you assign the command to a control, it subscribes to the CanExecuteChanged event. If you "redirect" it to the CommandManager.RequerySuggested event, the control will be notified whenever CommandManager.RequerySuggested is triggered.

like image 159
Thomas Levesque Avatar answered Oct 24 '22 18:10

Thomas Levesque