我有一个关于如何使用类从条目标签/视图绑定到视图模型的问题。每当我尝试将数据提交到我的视图模型类时,我都会有一个空值。
这是视图的代码:
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 项目的帮助。
您需要在视图模型构造函数中创建一个新的 User 实例。
public LoginPageViewModel(IApiService apiService, INavigationService navigationService)
{
this.apiService = apiService;
this.navigationService = navigationService;
LoginCommand = new DelegateCommand(Login);
this.User = new Users();
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句