JH_Dev
JH_Dev

Reputation: 446

Xamarin forms Commanding CanExecute does not update Button IsEnabled

I'm trying to apply a style to a button which has been disabled by a command.

I assumed the IsEnabled state was the property that was being triggered by the canexecutechanged event but it seems it does not.

What Button Property is being affected and can I hook into this event so that I can provide a style to the button?

Upvotes: 4

Views: 5479

Answers (2)

deloyar
deloyar

Reputation: 528

Here is the example to login when username length 11 and password at least one.

public class MainViewModel : BaseViewModel
{
    public Command LoginIn { get; set; }

    public MainViewModel()
    {
        LoginIn = new Command(async () => await SignIn(), (() => CanExecuteLogin));
    }
    private string _password;
    private string _username;
    public string UserName
    {
        get => _username;
        set
        {
            SetProperty(ref _username, value, nameof(UserName));
            SetProperty(ref _canExecuteLogin, IsExecutable(), nameof(CanExecuteLogin));
            LoginIn?.ChangeCanExecute();

        } 
    }

    public string Password
    {
        get => _password;
        set
        {
            SetProperty(ref _password, value, nameof(Password));
            SetProperty(ref _canExecuteLogin, IsExecutable(), nameof(CanExecuteLogin));
            LoginIn?.ChangeCanExecute();

        }
    }

    private bool _canExecuteLogin;

    public bool CanExecuteLogin
    {
        get => _canExecuteLogin;
        set => SetProperty(ref _canExecuteLogin, value, nameof(CanExecuteLogin));
    }

    public bool IsExecutable()
    {
        if (UserName != null && _password != null)
        {
            if (UserName.Length == 11 && _password.Length > 0)
                return true;
        }

            return false;
    }

    private async Task SignIn()
    { //Login Code here }

}

Upvotes: 2

Carlos Henrique
Carlos Henrique

Reputation: 373

In your viewmodel you can add a property that will lead to enable or disable its buttons. follows an example below.

public Command FacebookLoginCommand { get; set; }

private bool _IsBusy;
public override bool IsBusy
{
    get
    {
        return _IsBusy;
    }
    set
    {
        _IsBusy = value;
        OnPropertyChanged();
        FacebookLoginCommand?.ChangeCanExecute();
        GoogleLoginCommand?.ChangeCanExecute();
    }
}

public LoginViewModel(IUserDialogs dialogs) : base(dialogs)
{
    FacebookLoginCommand = new Command(async () =>
    {
        using (Dialogs.Loading("Carregando"))
        {
            IsBusy = true;
            await Task.Run(() => new FacebookLoginService(Dialogs).Logar());
            await Task.Run(() => Task.Delay(TimeSpan.FromSeconds(3)));
            IsBusy = false;
        }
    }, CanExecute());

    private Func<bool> CanExecute()
    {
        return new Func<bool>(() => !IsBusy);
    }
}

Upvotes: 8

Related Questions