75

Does anyone know how I can force CanExecute to get called on a custom command (Josh Smith's RelayCommand)?

Typically, CanExecute is called whenever interaction occurs on the UI. If I click something, my commands are updated.

I have a situation where the condition for CanExecute is getting turned on/off by a timer behind the scenes. Because this is not driven by user interaction, CanExecute is not called until the user interacts with the UI. The end result is that my Button remains enabled/disabled until the user clicks on it. After the click, it is updated correctly. Sometimes the Button appears enabled, but when the user clicks it changes to disabled instead of firing.

How can I force an update in code when the timer changes the property that affects CanExecute? I tried firing PropertyChanged (INotifyPropertyChanged) on the property that affects CanExecute, but that did not help.

Example XAML:

<Button Content="Button" Command="{Binding Cmd}"/>

Example code behind:

private ICommand m_cmd;
public ICommand Cmd
{
    if (m_cmd == null)
        m_cmd = new RelayCommand(
            (param) => Process(),
            (param) => EnableButton);

    return m_cmd;
}

// Gets updated from a timer (not direct user interaction)
public bool EnableButton { get; set; }
1
  • Did you try to raise INotifyPropertyChanged for the Command? You don't need to have a field for the Command, just return new one each time. This combination should work. Or create new Command only for the case when you need the forcing.
    – egaga
    Commented Feb 15, 2013 at 17:03

7 Answers 7

105

Calling System.Windows.Input.CommandManager.InvalidateRequerySuggested() forces the CommandManager to raise the RequerySuggested event.

Remarks: The CommandManager only pays attention to certain conditions in determining when the command target has changed, such as change in keyboard focus. In situations where the CommandManager does not sufficiently determine a change in conditions that cause a command to not be able to execute, InvalidateRequerySuggested can be called to force the CommandManager to raise the RequerySuggested event.

14
  • 1
    Do you suggest calling this from a ViewModel class?
    – Josh G
    Commented Apr 23, 2009 at 19:10
  • 3
    Not necessarily, as that may make your class hard to test. Try it, and move it into a service if necessary. Another option is to add a method to RelayCommand that allows you to raise CanExecuteChanged just for that command (CommandManager.InvalidRequerySuggested invalidates all commands, which is somewhat of an overkill). Commented Apr 23, 2009 at 19:15
  • 26
    Interesting... It works, but it has to be called on the UI thread. I'm not surprised.
    – Josh G
    Commented Apr 23, 2009 at 19:16
  • 4
    I used the MVVM-Light messenger and created a simple RefreshCommandStatus message that my ViewModels can now send out. The main window listens for this message and calls CommandManager.InvalidateRequerySuggest() Commented May 19, 2011 at 18:06
  • 6
    Must be run on UI Thread, so might as well do it like this: UI.Dispatcher.Invoke(() => { CommandManager.InvalidateRequerySuggested(); }); Commented Sep 27, 2016 at 16:02
29

I was aware of CommandManager.InvalidateRequerySuggested() a long time ago, and used it, but it wasn't working for me sometimes. I finally figured out why this was the case! Even though it doesn't throw like some other actions, you HAVE to call it on the main thread.

Calling it on a background thread will appear to work, but sometimes leave the UI disabled. I really hope this helps somebody, and saves them the hours I just wasted.

17

A workaround for that is binding IsEnabled to a property:

<Button Content="Button" Command="{Binding Cmd}" IsEnabled="{Binding Path=IsCommandEnabled}"/>

and then implement this property in your ViewModel. This also makes it a bit easier for the UnitTesting to work with the properties rather than commands to see if the command can be executed at a certain point of time.

I, personally, find it more convenient.

3
  • How do you refresh IsEnabled?
    – visc
    Commented Feb 15, 2016 at 16:28
  • I would avoid invalidating everything this is a better and easier solution
    – Asheh
    Commented Jul 12, 2016 at 9:59
  • #PersistentWPFIssues12YearAnniversary #NoWonderEverybodyFledToJS Commented Dec 7, 2020 at 18:17
6

Probably this variant will suit you:

 public interface IRelayCommand : ICommand
{
    void UpdateCanExecuteState();
}

Implementation:

 public class RelayCommand : IRelayCommand
{
    public event EventHandler CanExecuteChanged;


    readonly Predicate<Object> _canExecute = null;
    readonly Action<Object> _executeAction = null;

   public RelayCommand( Action<object> executeAction,Predicate<Object> canExecute = null)
    {
        _canExecute = canExecute;
        _executeAction = executeAction;
    }


    public bool CanExecute(object parameter)
    {
       if (_canExecute != null)
            return _canExecute(parameter);
        return true;
    }

    public void UpdateCanExecuteState()
    {
        if (CanExecuteChanged != null)
            CanExecuteChanged(this, new EventArgs());
    }



    public void Execute(object parameter)
    {
        if (_executeAction != null)
            _executeAction(parameter);
        UpdateCanExecuteState();
    }
}

Using simple:

public IRelayCommand EditCommand { get; protected set; }
...
EditCommand = new RelayCommand(EditCommandExecuted, CanEditCommandExecuted);

 protected override bool CanEditCommandExecuted(object obj)
    {
        return SelectedItem != null ;
    }

    protected override void EditCommandExecuted(object obj)
    {
        // Do something
    }

   ...

    public TEntity SelectedItem
    {
        get { return _selectedItem; }
        set
        {
            _selectedItem = value;

            //Refresh can execute
            EditCommand.UpdateCanExecuteState();

            RaisePropertyChanged(() => SelectedItem);
        }
    }

XAML:

<Button Content="Edit" Command="{Binding EditCommand}"/>
1
  • 1
    That is not ideal because it creates strong references to the handlers what leads to memory leaks. Commented Feb 4, 2015 at 15:54
4

Thanks guys for the tips. Here's a bit of code on how to marshal that call from a BG thread to the UI thread:

private SynchronizationContext syncCtx; // member variable

In the constructor:

syncCtx = SynchronizationContext.Current;

On the background thread, to trigger the requery:

syncCtx.Post( delegate { CommandManager.InvalidateRequerySuggested(); }, null );

Hope that helps.

-- Michael

2
  • 3
    Seems like it would be better to call Dispatcher.BeginInvoke()
    – Josh G
    Commented Mar 7, 2011 at 16:53
  • Hi Josh. Maybe it would be better. Internally, Dispatcher.BeginInvoke() uses the SynchronizationContextSwitcher class which delegates to the SynchronizationContext anyway... Commented Apr 6, 2011 at 0:24
0

To update only a single GalaSoft.MvvmLight.CommandWpf.RelayCommand you could use

mycommand.RaiseCanExecuteChanged();

and for me i've created an Extension method:

public static class ExtensionMethods
    {
        public static void RaiseCanExecuteChangedDispatched(this RelayCommand cmd)
        {
            System.Windows.Application.Current.Dispatcher.Invoke(DispatcherPriority.Normal, new Action(() => { cmd.RaiseCanExecuteChanged(); }));
        }

        public static void RaiseCanExecuteChangedDispatched<T>(this RelayCommand<T> cmd)
        {
            System.Windows.Application.Current.Dispatcher.Invoke(DispatcherPriority.Normal, new Action(() => { cmd.RaiseCanExecuteChanged(); }));
        }
    }
0

Didn't see this mentioned here so adding in 2023.

I sorted this issue by installing the Prism library via NuGet (VS suggested it to me for "DelegateCommand") and used DelegateCommand instead of own RelayCommand implementation. I then just called command.RaiseCanExecuteChanged() the same way I would call OnPropertyChanged(propName). Works great for me.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.