Why WPF button's command's CanExecute method is not called even if I call CommandManager.InvalidateRequerySuggested()?

后端 未结 1 1010
说谎
说谎 2021-01-20 09:55

I\'m facing the same issue reported in these questions:

Button Command CanExecute not called when property changed

How can I force a textbox change to enable

相关标签:
1条回答
  • 2021-01-20 10:21

    While the "PropertyChanged" events are automatically marshalled, the call to CommandManager.InvalidateRequerySuggested() is not.

    So to fix the issue just ensure the call is made on the Dispatcher thread as follows:

        private void DataContext_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            switch (e.PropertyName)
            {
                case "Ready":
                    var d = Application.Current.Dispatcher;
                    if (d.CheckAccess())
                        CommandManager.InvalidateRequerySuggested();
                    else
                        d.BeginInvoke((Action)(() => { CommandManager.InvalidateRequerySuggested(); }));
                    break;
            }
        }
    

    Be careful when relying on property changes that are triggered by asynchronous tasks.

    I hope this can help some of you in saving some days of work...

    0 讨论(0)
提交回复
热议问题