Why people use CommandManager.InvalidateRequerySuggested() on ICommands?

后端 未结 4 976
悲哀的现实
悲哀的现实 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:50

    This question is quite old, it's 2019 now, but I have found another reason to use CommandManager.InvalidateRequerySuggested().

    I have written my own custom ICommand class for a WPF application, in which I invoked CanExecuteChanged directly in the first place like this.

    public void RaiseCanExecuteChanged()
    {
        CanExecuteChanged?.Invoke(this, null); 
    }
    

    My WPF application makes heavy use of different threads and when the above method is called from another thread then the main UI thread, it throws no error, it is just kind of ignored. It was getting even worse, when I found out, that all code lines inside the calling method were skipped, which led to strange results.

    I don't know exactly, but I guess the reason was, that CanExecuteChanged led to changes in my UI, which must not be changed from another thread.

    However - the moment when I changed my ICommand to CommandManager.InvalidateRequerySuggested(), there was no more problem. It seems that CommandManager.InvalidateRequerySuggested() can be called from any thread and the UI still gets updated.

    public event EventHandler CanExecuteChanged
    {
        add { CommandManager.RequerySuggested += value; }
        remove { CommandManager.RequerySuggested -= value; }
    }
    
    public void RaiseCanExecuteChanged()
    {
        CommandManager.InvalidateRequerySuggested();
    }
    

    I thought this could be a valueable answer, because I debugged this issue for 3 hours, before I came to this solution. The problem finding this issue was, that there were no errors thrown while debugging. The code was just skipped. Very strange behaviour.

提交回复
热议问题