Kshitij
Kshitij

Reputation: 392

Bind controls with Model object in ViewModel class in Xamarin forms

I am learning MVVM in Xamarin forms using Prism. I have implemented a login functionality which uses a User model class. But the bindings are not working. Please review the code and suggest corrections.

I am not sure how to bind the control's text property to the Model class object's properties.

LoginPage.xaml

   <?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:prism="http://prismlibrary.com"
             prism:ViewModelLocator.AutowireViewModel="True"
             x:Class="LeaveTracker.Views.LoginPage"
             Title="{Binding Title}">

    <StackLayout Orientation="Vertical" BindingContext="{Binding UserObj}">
        <Entry Placeholder="User ID" Text="{Binding UserID}"/>
        <Entry Placeholder="Password" Text="{Binding Password}" IsPassword="True"/>
    </StackLayout>
</ContentPage>

LoginPageViewModel.cs

 public class LoginPageViewModel : ViewModelBase
    {
        private User _user;
        private IFirebaseService _firebaseService;

        public User UserObj
        {
            get { return _user; }
            set { SetProperty(ref _user, value); }
        }

        public DelegateCommand LoginCommand { get; set; }

        public LoginPageViewModel(IFirebaseService firebaseService, INavigationService navigationService) : base(navigationService)
        {
            Title = "Log In";
            _firebaseService = firebaseService;
            LoginCommand = new DelegateCommand(Login, CanLogin);
        }

        private void Login()
        {
            var x = _firebaseService.LoginAsync(_user);
        }

        private bool CanLogin()
        {
            if (string.IsNullOrEmpty(_user.UserID) && string.IsNullOrEmpty(_user.Password))
            {
                return true;
            }

            return false;
        }

User.cs

  public class User
    {
        private string _userID;

        public string UserID
        {
            get { return _userID; }
            set { _userID = value; }
        }

        private string _password;

        public string Password
        {
            get { return _password; }
            set { _password = value; }
        }



    }

Upvotes: 0

Views: 2460

Answers (1)

Jason
Jason

Reputation: 89179

your BindingContext is LoginPageViewModel, and UserObj is a property of the VM, so your binding path needs to include UserObj

<Entry Placeholder="User ID" Text="{Binding UserObj.UserID}"/>
<Entry Placeholder="Password" Text="{Binding UserObj.Password}" IsPassword="True"/>

Upvotes: 2

Related Questions