【问题标题】:How to data bind from view to view model in Xamarin?如何在 Xamarin 中将数据从视图绑定到视图模型?
【发布时间】:2017-06-05 14:55:45
【问题描述】:

我有一个关于如何使用类从条目标记/视图绑定到视图模型的问题。每当我尝试将数据提交到我的视图模型类时,我都会得到一个空值。

这是视图的代码:

Entry Text="{Binding User.UserName, Mode=TwoWay}"/>
<Entry Text="{Binding User.Password, Mode=TwoWay}"/>

<Button Text="Login" Command="{Binding LoginCommand}"/>

这是视图模型(构造函数部分)的代码:

 public LoginPageViewModel(IApiService apiService, INavigationService navigationService)
    {
        this.apiService = apiService;
        this.navigationService = navigationService;
        LoginCommand = new DelegateCommand(Login);
    }

在视图模型中,我还有一个用户名和密码类,它使用用户模型:

 private Users user;
    public Users User
    {
        get { return user; }
        set { SetProperty(ref user, value); }
    }

这是用户的模型:

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

}

每次我尝试点击提交按钮时,我都会在尝试调试代码时得到空值。

private async void Login()
    {
        var test = User.UserName;

        bool success = await apiService.LoginAsync(User);

感谢您对我的 Xamarin 项目的帮助。

【问题讨论】:

  • 当你创建 LoginViewModel 时,它是实例化一个新的 User 实例,还是只是 null?
  • @Jason 根本就是空值。

标签: c# xamarin xamarin.forms


【解决方案1】:

您需要在视图模型构造函数中创建一个新的 User 实例。

public LoginPageViewModel(IApiService apiService, INavigationService navigationService)
    {
        this.apiService = apiService;
        this.navigationService = navigationService;
        LoginCommand = new DelegateCommand(Login);

        this.User = new Users();
    }

【讨论】:

  • 谢谢。你能找到一个例子吗?
  • 谢谢@Jason 和@Diego!太棒了!
猜你喜欢
  • 2013-09-25
  • 2020-01-29
  • 1970-01-01
  • 1970-01-01
  • 2020-06-08
  • 1970-01-01
  • 2020-06-20
  • 2017-06-03
  • 2020-01-21
相关资源
最近更新 更多