Why people use CommandManager.InvalidateRequerySuggested() on ICommands?

后端 未结 4 975
悲哀的现实
悲哀的现实 2021-02-20 17:23

I am making some custom ICommand implementation of my own and I see A LOT of implementations going like this:

public event EventHandler CanExecuteChanged
{
    a         


        
4条回答
  •  谎友^
    谎友^ (楼主)
    2021-02-20 17:31

    This is an answer to this answer. It is true that the CanExecuteChanged?.Invoke(this, null); has to be called by the main UI thread.

    Simply write it like follows:

    public void RaiseCanExecuteChanged()
    {
        Application.Current.Dispatcher.Invoke(() => CanExecuteChanged?.Invoke(this, null)); 
    }
    

    This solves your problem and you can requery just one command. It is however true that you should nevertheless make your CanExecute-Method as fast as possible, as it will anyways be periodically executed. It is best to have CanExecute just consist of a single return foo; where foo is a field you can set right before you call CommandManager.InvalidateRequerySuggested();.

提交回复
热议问题