After the help of William and Xamarin support, I was finally able to find how functionality works.
It is a bit counter intuitive as we expect to Enable/Disable the button (ToolbarItem), but we actually have to manage the state of the command that is bound to the button. Once we understand this pattern, it makes sense.
The Command object of type ICommand, has a CanExecute property (thank you William for pointing it out)
Now you don't want to access/use it directly unless it is for actually checking if the command can be executed or not.
Wherever you see fit in your code, to change the state of the command, you need to add the following line:
((Command)_myCommand).ChangeCanExecute();
This line will force the CanExecute property to be re-evaluated for the specified command.
I personally decided to add it where I track the inactivity as it made sense in my application.
public bool Inactive {
get {
return _inactive;
}
set {
if (_inactive != value) {
_inactive = value;
((Command)_myCommand).ChangeCanExecute();
OnPropertyChanged ();
}
}
}
In the View, there are no changes to be noted:
<ToolbarItem Text="Run" Command="{Binding MyCommand}" />
Now when you create the Command object is where the big work will be done. We usually use the single argument constructor as it is generally enough and it is where we define what our command does. Interestingly enough, there is a 2 parameter constructor as well where you can provide the function/action that determines the value of the CanExecute property.
_myCommand = new Command (async () => {
Inactive = false;
await Run();
Inactive = true;
},
() => {
return Inactive;
});
public ICommand MyCommand {
get {
return _myCommand;
}
}
Edit: I know you that technically changing the value of Inactive should happen in Run(), but for demonstration purposes...
IsEnabled
property. Though, I can't still change the value once set. – testing