Hello,
Welcome to our Microsoft Q&A platform!
I expected the Button to be enabled/disabled like in a "normal" ContentView/ContentPage, setting the CanExecute-Method in my ViewModel to true or false.
To change the status of the command's 'CanExecute', try using Command(Action, Func<Boolean>)
constructor method. The second parameter indicates if the Command can be executed. Create a 'bool' property in the model class and then call Command.ChangeCanExecute
method when the property is changed.
Here the sample code you could refer to:
public class MainPageModel : INotifyPropertyChanged
{
public Command BtnCommand { get; set; }
public MainPageModel()
{
BtnCommand = new Command(() =>
{
App.Current.MainPage.DisplayAlert("title", "message", "cancel");
}, () => IsBtnEnabled);
}
private bool isBtnEnabled;
public bool IsBtnEnabled
{
get
{
return isBtnEnabled;
}
set
{
if (isBtnEnabled != value)
{
isBtnEnabled = value;
BtnCommand.ChangeCanExecute(); //
NotifyPropertyChanged();
}
}
}
protected virtual void NotifyPropertyChanged([CallerMemberName] string propertyName = "")
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
public event PropertyChangedEventHandler PropertyChanged;
}
You could set binding to the button's IsEnabled
property to enable/disable the button directly.
Button Command="{Binding ClickCommand}" IsEnabled="{Binding IsBtnEnabled}"/>
Best Regards,
Jarvan Zhang
If the response is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.