CommandManager.InvalidateRequerySuggested does not cause a requery on CanExecute in MVVM-Light

£可爱£侵袭症+ 提交于 2019-12-03 13:07:32
Minh Nguyen

I would turn the isRevertEnabled flag into a property and call the OnPropertyChanged method from there (you need to implement the INotifyPropertyChanged interface). At the point where you change the flag, you need to use the property, e.g. IsRevertEnabled = true.

private bool isRevertEnabled;

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

private bool CanRevertExecute()     
{         
    return IsRevertEnabled;     
}

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

blindmeis

There are a lot suggestions out there (here, here, here).

I use a simple but not so beautiful workaround. I simply call OnPropertyChanged("MyICommand") for my commands in my BackgroundWorker Completed Event.

Andrea

According to Josh Smith's article 'Allowing CommandManager to query your ICommand objects'. The problem is that the command is a non-routed command.

I have made a new implementation of the 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);
    //            }
}
Bradman

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

Just call Revert.RaiseCanExecuteChanged();

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!