简体   繁体   中英

How to data bind from view to view model in Xamarin?

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.

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();
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM