Reputation: 55
I have a question on how to bind from entry tag/view to view model using a class. I'm having a null value whenever I try to submit the data going to my view model class.
Here is the code for the view:
Entry Text="{Binding User.UserName, Mode=TwoWay}"/>
<Entry Text="{Binding User.Password, Mode=TwoWay}"/>
<Button Text="Login" Command="{Binding LoginCommand}"/>
Here is the code for the view model(constructor part):
public LoginPageViewModel(IApiService apiService, INavigationService navigationService)
{
this.apiService = apiService;
this.navigationService = navigationService;
LoginCommand = new DelegateCommand(Login);
}
In the view model, I have also a class for the username and password where it uses the model of User:
private Users user;
public Users User
{
get { return user; }
set { SetProperty(ref user, value); }
}
Here is the model for the Users:
public class Users : BindableObject
{
private string username;
public string UserName
{
get { return username; }
set { username = value; }
}
private string password;
public string Password
{
get { return password; }
set { password = value; }
}
}
Every time I tried to hit the submit button, I get the null value when I tried to debug my code.
private async void Login()
{
var test = User.UserName;
bool success = await apiService.LoginAsync(User);
Thank you for your help on my Xamarin project.
Upvotes: 0
Views: 700
Reputation: 5313
You need to create a new instance of User at your viewmodel constructor.
public LoginPageViewModel(IApiService apiService, INavigationService navigationService)
{
this.apiService = apiService;
this.navigationService = navigationService;
LoginCommand = new DelegateCommand(Login);
this.User = new Users();
}
Upvotes: 1