Enable a button in MVVM

Eduardo Gomez 3,426 Reputation points
2021-06-16T01:29:51.797+00:00

Hello Microsoft

I Manege to disable and enable the button on Register, but I want to do the same with Login

VM

[AddINotifyPropertyChangedInterface]
public class LoginViewModel {
public ICommand OpenPopupCommand { get; set; }
public Command Register { get; set; }
public Command Login { get; set; }
public bool DisplayPopUp { get; set; }
public User User { get; set; }
public bool RegisterAllowed { get; set; }
public bool LoginAllowed { get; set; }

    public LoginViewModel() {
        User = new User {
            OnAnyOfMyPropertiesChanged = () => Register.ChangeCanExecute()
        };
        OpenPopupCommand = new Command(() => {
            DisplayPopUp = true;
        });
        Register = new Command(
            execute: () => {
                Debug.WriteLine(User);
            },
            canExecute: () => {
                RegisterAllowed = User != null
                && !string.IsNullOrEmpty(User.Email)
                && !string.IsNullOrEmpty(User.Password)
                && User.Password.Equals(User.ConfirmPassword);
                return RegisterAllowed;
            });
        Login = new Command(
            execute: () => {
                Debug.WriteLine(User);
            },
            canExecute: () => {
                LoginAllowed = User != null
                && !string.IsNullOrEmpty(User.Email)
                && !string.IsNullOrEmpty(User.Password);
                return RegisterAllowed;
            });
    }
}

}

Xamarin
Xamarin
A Microsoft open-source app platform for building Android and iOS apps with .NET and C#.
5,338 questions
0 comments No comments
{count} votes

Accepted answer
  1. JessieZhang-MSFT 7,706 Reputation points Microsoft Vendor
    2021-06-16T06:25:44.017+00:00

    Hello,

    Welcome to our Microsoft Q&A platform!

    You can use the canExecute parameter of command Register to achieve this.
    Please refer to the following code,I tested on my side,it works properly.

    1. implement interface INotifyPropertyChanged for class User

    User.cs

    public class User: INotifyPropertyChanged  
    {  
        //public string Email { get; set; }  
        private string _email;  
        public string Email  
        {  
            set { SetProperty(ref _email, value); }  
            get { return _email; }  
        }  
    
        //public string Password { get; set; }  
        private string _password;  
        public string Password  
        {  
            set { SetProperty(ref _password, value); }  
            get { return _password; }  
        }  
    
        //public string ConfirmPassword { get; set; }  
    
        private string _confirmPassword;  
        public string ConfirmPassword  
        {  
            set { SetProperty(ref _confirmPassword, value); }  
            get { return _confirmPassword; }  
        }  
    
        bool SetProperty<T>(ref T storage, T value, [CallerMemberName] string propertyName = null)  
        {  
            if (Object.Equals(storage, value))  
                return false;  
    
            storage = value;  
            OnPropertyChanged(propertyName);  
            return true;  
        }  
    
        protected void OnPropertyChanged([CallerMemberName] string propertyName = null)  
        {  
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));  
        }  
    
        public event PropertyChangedEventHandler PropertyChanged;  
    }  
    
    1. implement interface INotifyPropertyChanged for class LoginViewModel .

    LoginViewModel.cs

    public class LoginViewModel: INotifyPropertyChanged  
    {  
        public ICommand OpenPopupCommand { get; set; }  
        public ICommand Register { get; set; }  
        public bool DisplayPopUp { get; set; }  
        //public User User { get; set; }  
    
        User userEdit;  
        public User UserEdit  
        {  
            set {   
                SetProperty(ref userEdit, value);  
            }  
            get {   
                return userEdit;  
              
            }  
        }  
    
        public LoginViewModel()  
        {  
            userEdit = new User();  
    
            userEdit.PropertyChanged += OnPersonEditPropertyChanged;  
            RegisterAllowed = false;  
    
            OpenPopupCommand = new Command(() => {  
                DisplayPopUp = true;  
            });  
    
            //Register = new Command(RegisterClicked, RegisterAllowed);  
    
            Register = new Command(  
            execute: () =>  
            {  
                UserEdit.PropertyChanged -= OnPersonEditPropertyChanged;  
                userEdit = null;  
                RegisterAllowed = false;  
                RefreshCanExecutes();  
                Debug.WriteLine("++++++++++ Email = " + userEdit.Email +"<--> password = " + userEdit.Password + "<--> ConfirmPassword = " + userEdit.ConfirmPassword);  
            },  
            canExecute: () =>  
           {  
               if (userEdit != null && !string.IsNullOrEmpty(userEdit.Email) && !string.IsNullOrEmpty(userEdit.Password) && userEdit.Password.Equals(userEdit.ConfirmPassword))  
               {  
                   RegisterAllowed = true;  
               }  
               else  
               {  
                   RegisterAllowed = false;  
               }  
    
               return RegisterAllowed;  
            });  
    
        }  
    
    
        void OnPersonEditPropertyChanged(object sender, PropertyChangedEventArgs args)  
        {  
            (Register as Command).ChangeCanExecute();  
        }  
    
        void RefreshCanExecutes()  
        {  
            (Register as Command).ChangeCanExecute();  
        }  
    
        //public bool RegisterAllowed(object obj) =>  
        //    !string.IsNullOrEmpty(User.Email) && !string.IsNullOrEmpty(User.Password) && User.Password.Equals(User.ConfirmPassword);  
    
    
        private bool _registerAllowed;  
    
        public bool RegisterAllowed  
        {  
            set { SetProperty(ref _registerAllowed, value); }  
            get { return _registerAllowed; }  
        }  
    
        bool SetProperty<T>(ref T storage, T value, [CallerMemberName] string propertyName = null)  
        {  
            if (Object.Equals(storage, value))  
                return false;  
    
            storage = value;  
            OnPropertyChanged(propertyName);  
            return true;  
        }  
    
        protected void OnPropertyChanged([CallerMemberName] string propertyName = null)  
        {  
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));  
        }  
    
        public event PropertyChangedEventHandler PropertyChanged;  
    }  
    

    3.change yourPage.xaml as follows:

    <?xml version="1.0" encoding="utf-8" ?>  
    <ContentPage xmlns="http://xamarin.com/schemas/2014/forms"  
                 xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" xmlns:fodyapp1="clr-namespace:FodyApp1"  
                 x:Class="FodyApp1.MainPage">  
      
        <ContentPage.BindingContext>  
            <fodyapp1:LoginViewModel></fodyapp1:LoginViewModel>  
        </ContentPage.BindingContext>  
     
      
        <StackLayout>  
            <StackLayout BackgroundColor="CornflowerBlue"  BindingContext="{Binding UserEdit}"  
      Spacing="20"  
      Padding="10">  
                <Entry Placeholder="Email"  
        Text="{x:Binding Email, Mode=TwoWay}"/>  
                <Entry Placeholder="Password"  
        Text="{x:Binding Password, Mode=TwoWay}"/>  
                <Entry Placeholder="Confirm Password"  
        Text="{x:Binding ConfirmPassword, Mode=TwoWay}"/>  
      
            </StackLayout>  
      
            <Button Text="Sign in"  
               Command="{x:Binding Register}"/>  
      
        </StackLayout>  
      
    </ContentPage>  
    

    Note:

    1. To compare two strings, we should use Equals instead of ==;
    2. Besides,maybe you confused the logical relationship between the two variables ( User.Password and User.ConfirmPassword),
      The code should be User.Password.Equals(User.ConfirmPassword)
      not User.Password != User.ConfirmPassword

    Update:

    I Manege to disable and enable the button on Register, but I want to do the same with Login

    I achieved this function on my demo, you can refer to the following code:

    LoginViewModel.cs

       public class LoginViewModel: INotifyPropertyChanged  
        {  
            public ICommand OpenPopupCommand { get; set; }  
            public ICommand Register { get; set; }  
      
            public ICommand Login { get; set; }  
      
            public bool RegisterAllowed { get; set; }  
            public bool LoginAllowed { get; set; }  
      
            public bool DisplayPopUp { get; set; }  
            //public User User { get; set; }  
      
            User userEdit;  
            public User UserEdit  
            {  
                set {   
                    SetProperty(ref userEdit, value);  
                }  
                get {   
                    return userEdit;  
                  
                }  
            }  
      
            public LoginViewModel()  
            {  
                userEdit = new User();  
      
                userEdit.PropertyChanged += OnPersonEditPropertyChanged;  
      
                RegisterAllowed = false;  
      
                OpenPopupCommand = new Command(() => {  
                    DisplayPopUp = true;  
                });  
      
      
                Register = new Command(  
                execute: () =>  
                {  
                    UserEdit.PropertyChanged -= OnPersonEditPropertyChanged;  
                    userEdit = null;  
                    RegisterAllowed = false;  
                    RefreshCanExecutes();  
                    Debug.WriteLine(" Email = " + userEdit.Email +"<--> password = " + userEdit.Password + "<--> ConfirmPassword = " + userEdit.ConfirmPassword);  
                },  
                canExecute: () =>  
               {  
                   RegisterAllowed = userEdit != null  
                    && !string.IsNullOrEmpty(userEdit.Email)  
                    && !string.IsNullOrEmpty(userEdit.Password)  
                    && userEdit.Password.Equals(userEdit.ConfirmPassword);  
                   return RegisterAllowed;  
               });  
      
                Login = new Command(  
                 execute: () => {  
                     RefreshCanExecutes();  
                     Debug.WriteLine(" Email = " + userEdit.Email + "<--> password = " + userEdit.Password + "<--> ConfirmPassword = " + userEdit.ConfirmPassword);  
                 },  
             canExecute: () => {  
                LoginAllowed = (userEdit != null  
                && !string.IsNullOrEmpty(userEdit.Email)  
                && !string.IsNullOrEmpty(userEdit.Password));  
                return LoginAllowed;  
                 });  
      
            }  
      
      
            void OnPersonEditPropertyChanged(object sender, PropertyChangedEventArgs args)  
            {  
                (Register as Command).ChangeCanExecute();  
      
                (Login as Command).ChangeCanExecute();  
            }  
      
      
            void RefreshCanExecutes()  
            {  
                (Register as Command).ChangeCanExecute();  
      
                (Login as Command).ChangeCanExecute();  
            }  
      
      
            bool SetProperty<T>(ref T storage, T value, [CallerMemberName] string propertyName = null)  
            {  
                if (Object.Equals(storage, value))  
                    return false;  
      
                storage = value;  
                OnPropertyChanged(propertyName);  
                return true;  
            }  
      
            protected void OnPropertyChanged([CallerMemberName] string propertyName = null)  
            {  
                PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));  
            }  
      
            public event PropertyChangedEventHandler PropertyChanged;  
        }  
    

    Best Regards,

    Jessie 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.


0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.