简体   繁体   中英

Wpf UI does not update

I have a wpf mvvm application. There is a button in the view and it is bound to a command in the view model. The function CanExecute of this command returns the value of some bool property

private bool Command1CanExecute()
{
    return IsConnected;
}

When the property is changed, the button should become disabled but it's doesn't happened until I click somewhere in UI. The solution I have thought about (and it works :) ) is to run

  CommandManager.InvalidateRequerySuggested();

each second (Dispatcher timer can do it).

Is there another, more elegant solution for my problem? Thank you.

Matvey.

All Commands are updated after any userinteraction. If you change a property programmatically and want to update the command-states you have to suggest a requery after your property has changed:

CommandManager.InvalidateRequerySuggested();

you can also raise a CanExecuteChanged-Event of your command (which simply does nothing else than above)

Command1.RaiseCanExecuteChanged();

you'd insert any of this in the setter of IsConnected like following

private bool _isConnected;
public bool IsConnected
{
  get { return _isConnected; }
  set
  {
    if (_isConnected != value)
    { 
      _isConnected = value;
      RaisePropertyChanged(); //or something similar
      Command1.RaiseCanExecuteChanged();
    }
  }
}

if you don't want that, you can just return true in your CanExecute-Handler and bind IsEnabled of your button to the property itself.

<Button IsEnabled="{Binding IsConnected}" Command="{Binding Command1}" ... />

For those who uses MicroMvvm the change needs to be applied to the class: public class RelayCommand<T>:ICommand

and method:

 [DebuggerStepThrough]
        public Boolean CanExecute(Object parameter)
        {

            var valu = _canExecute == null ? true : _canExecute();
            CommandManager.InvalidateRequerySuggested();
            return valu;
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM