CommandManager.InvalidateRequerySposed does not trigger a CanExecute request in MVVM-Light

I am using MVVM-Light RelayCommand

private ICommand myRevertCmd; public ICommand Revert { get { if (myRevertCmd == null) { myRevertCmd = new RelayCommand(RevertExecute, CanRevertExecute); } return myRevertCmd; } } private void RevertExecute() { searchType = SearchType.Revert; SearchStart(); } private bool CanRevertExecute() { return isRevertEnabled; } 

I have code that changes the value of isRevertEnabled, but the associated button does not change. After some searching, I found that you can use to reevaluate button states

 // force the GUI to re-evaluate the state of the buttons CommandManager.InvalidateRequerySuggested(); 

But that does not work. Does anyone have any suggestions?

+6
source share
6 answers

I would include the isRevertEnabled flag in the property and call the OnPropertyChanged method (you need to implement the INotifyPropertyChanged interface). The moment you change the flag, you need to use a property, for example. IsRevertEnabled = true.

 private bool isRevertEnabled; public bool IsRevertEnabled { get { return isRevertEnabled; } set { if (isRevertEnabled != value) { isRevertEnabled = value; OnPropertyChanged("IsRevertEnabled"); } } } private bool CanRevertExecute() { return IsRevertEnabled; } 
0
source

To add another possible solution, in my case I needed to call CommandManager.InvalidateRequerySuggested in the CommandManager.InvalidateRequerySuggested thread using Application.Current.Dispatcher.Invoke .

+25
source

There are many suggestions ( here , here , here ).

I use a simple but not very nice workaround. I simply call OnPropertyChanged("MyICommand") for my commands in my BackgroundWorker completed event.

+7
source

According to Josh Smith's article, "Allow CommandManager to request your ICommand objects . " The problem is that a team is a non-routing team.

I made a new implementation of MVVM-Light RelayCommand as follows:

 // original //public event EventHandler CanExecuteChanged; public event EventHandler CanExecuteChanged { add { CommandManager.RequerySuggested += value; } remove { CommandManager.RequerySuggested -= value; } } public void RaiseCanExecuteChanged() { CommandManager.InvalidateRequerySuggested(); // var handler = CanExecuteChanged; // if (handler != null) // { // handler(this, EventArgs.Empty); // } } 
+3
source

I think you can call the " Revert.RaiseCanExecuteChanged() " method with the INPC set method (or the dependency property) " isRevertEnabled ". This will force the predicate " CanRevertExecute ".

0
source

Just call Revert.RaiseCanExecuteChanged();

0
source

Source: https://habr.com/ru/post/888299/


All Articles