Realtime validation of a button, using fody

133 Views Asked by At

I a trying to disable and enable a button based on user input. I implemented fody property changed Nuget package, to help me reduce my code a bit.

and it works, when I start typing, the breakpoint in my LoginViewModel gets hit and display my values ViewModel getting hit every time I type

but I can't seem to trigger CanLogin() method

   [AddINotifyPropertyChangedInterface]
    public class LoginPageViewModel {

        public ICommand OpenRegisterPopupCommand { get; set; }

        public ICommand Register { get; set; }

        public ICommand Login { get; set; }

        public Users Users { get; set; }

        public bool IsPopUpOpen { get; set; }

        public LoginPageViewModel() {

            Users = new Users();

            Login = new Command(LoginAction, CanLogin);

            Register = new Command(RegisterAction);

            OpenRegisterPopupCommand = new Command(() => {
                IsPopUpOpen = true;
            });
        }

        private void LoginAction(object obj) {
            throw new NotImplementedException();
        }

        private bool CanLogin(object arg) {
            if (Users != null && !string.IsNullOrEmpty(Users.Email) && !string.IsNullOrEmpty(Users.Password)) {

                return true;
            }

            return false;
        }
1

There are 1 best solutions below

6
On

You are using a Command with a CanExecute method. If the CanExecute method returns false, the command will not ve able to be executed. But this validation does not happen all the time, you have to trigger it.

You have to call Login.ChangeCanExecute() when you modify any of the related properties (like Users, Users.Email or Users.Password), this will fire the CanExecute validation of the command.

Command documentation.