Reputation: 5072
Sometimes when I bind to commands to a ViewModel, my CanExecute code does not always get called and hence my buttons are not disabled when they should be.
Any ideas?
Thanks
Upvotes: 1
Views: 526
Reputation: 9030
When canExecute is not called the first time, that's a binding problem.
If it's not 'automatically' called second,[n]th time, that's the normal behavior.
Imagine, how the UI should know that it should requery your predicate? When you have a command parameter it will call your predicate every time the parameter changes. Generally, some UI 'events' also requery it (focus, updatelayout etc), but not always (that's good, it would be pointless to reevaluate every command binding all time). So you cannot rely on it. You make the business logic, so you know when it needs an update, not the UI. The UI 'cannot see inside your predicate delegate' and watch what happens. You have to notify the UI about it, same as you notify when a property changed.
ICommand has an event, so you must implement it, it's the CanExecuteChanged.
You should implement a public method to fire it (or it is already implemented if you use a framework, like MVVMLight or Prism).
A simple implementation.
public void RaiseCanExecuteChanged()
{
var handler = CanExecuteChanged;
if (handler != null)
{
handler(this, EventArgs.Empty);
}
}
So you can call it on your command whenever your canExecute state changes in your business logic and it is going to notify all the subscribers, which is your button in this case.
Upvotes: 1
Reputation: 1120
You mention the state of the button not being disabled. This seems more like a binding issue than binding to commands. Is the state of the property you are binding to changing? When is it changing, etc.?
Upvotes: 0