App
App

Reputation: 356

How can I call CanExecute from an event to disable the Command?

I have a command "ShowDataCommand" with a CanExecute method.

public override bool CanExecute(object parameter)
{
    return _someFacade.CanCommandEnable();
}

When I launch my application, CanExecute gets called and depending on the value returned from facade, it either enables or disables the command.

Now new requirement is that, there is a button in the main page. When user clicks that button a dialog opens and till the time dialog is open the "ShowDataCommand" should be disable.

There is already an event fired when dialog is open and when dialog is closed. I have subscribed the event in the command. The event fires with appropriate true and false value.

Now I don't know how can I disable the Command from this event? Can I somehow raise CanExecute with this new value?

Upvotes: 0

Views: 218

Answers (1)

mm8
mm8

Reputation: 169220

You can force the CanExecute method of your command to get called again by raising the CanExecuteChanged event.

Most ICommand implementations have a method for raising this event so if you are using your own implementation you could add a method to your class and call it whenever you want to "refresh" the command, for example when your button is clicked:

public class YourCommandClass : ICommand
{
    ...
    public void RaiseCanExecuteChanged() //<-- call this method
    {
        var handler = CanExecuteChanged;
        if (handler != null)
            handler(this, EventArgs.Empty);
    }
}

Please refer to the RelayCommand class in MvvmLight for an example of an ICommand implementation: https://github.com/paulcbetts/mvvmlight/blob/dce4e748c538ed4e5f5a0ebbfee0f54856f52dc6/GalaSoft.MvvmLight/GalaSoft.MvvmLight%20(NET35)/Command/RelayCommand.cs

Upvotes: 1

Related Questions