Reputation: 163
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.
Upvotes: 0
Views: 1393
Reputation: 1579
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;
}
Upvotes: -1
Reputation: 2999
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}" ... />
Upvotes: 3