我正在使用带MVVM模式的Xamarin.Forms。我在这里尝试做的是从用户获取文本(电子邮件,密码,确认密码)并将其发送到viewmodel。现在我已经有了一个具有这三个属性的'RegisterBindingModel.cs'类
因此,而不是视图模型中的此代码
public string Email { get; set; }
public string Password { get; set; }
public string ConfirmPassword { get; set; }
我用过这段代码
public RegisterBindingModel RegisterBindingModel { get; set; }
但是在编辑后调试时我得到一个null RegisterBindingModel。
xaml页面内容和line BindingContext="{Binding RegisterBindingModel}
已从stacklayout标记中删除
<StackLayout HorizontalOptions="CenterAndExpand">
<Label Text="Register Now! "/>
<StackLayout BindingContext="{Binding RegisterBindingModel}">
<Entry Text="{Binding Email}" Placeholder="Email" />
<Entry Text="{Binding Password}" IsPassword="True" Placeholder="Password" />
<Entry Text="{Binding ConfirmPassword}" IsPassword="True" Placeholder="ConfirmPassword" />
</StackLayout>
<Button Text="Register" Command="{Binding RegisterCommand}" />
</StackLayout>
在Registerpage.xaml.cs中我使用了这行代码:
BindingContext = new RegisterViewModel(Navigation);
和RegisterBindingModel类:
public class RegisterBindingModel
{
public string Email { get; set; }
public string Password { get; set; }
public string ConfirmPassword { get; set; }
}
请求编辑
private async void Register()
{
var isSuccess = await _identityService.RegisterAsync(RegisterBindingModel);
}
那么在我改变代码后出了什么问题?
首先让我们更新你的RegisterBindingModel。我们需要添加存储数据的私有字段。您用于绑定的公共属性将设置/获取此数据。我们想在MVVM中这样做的原因是我们可以利用双向绑定。将来如果要将这些字段的值设置为某些内容并使视图更新。这会很有帮助。它还有助于将更新绑定代码整合到属性设置器中。
public class RegisterBindingModel : BindableBase
{
private string _email;
public string Email {
get{
return this._email;
}
set{
if ( !string.IsNullOrEmpty(value) )
{
SetProperty(ref this._email, value);
}
}
}
private string _password;
public string Password {
get{
return this._password;
}
set{
if ( !string.IsNullOrEmpty(value) )
{
SetProperty(ref this._password, value);
}
}
}
private string _confirmPassword;
public string ConfirmPassword {
get{
return this._confirmPassword;
}
set{
if ( !string.IsNullOrEmpty(value) )
{
SetProperty(ref this._confirmPassword, value);
}
}
}
}
接下来,您是否决定是否要使用MVVM框架(即PRISM,MVVMCross等),那里有很多。这取决于个人的偏好。我偏爱PRISM。 Prism有一个ViewmodelBase和BindableBase类,可以为您的视图模型扩展。它已经实现了INotifyPropertyChanged接口。
正如elgonzo所述,更新您的RegisterViewModel。
public class RegisterViewModel : BindableBase
{
private RegisterBindingModel _registerBindingModel;
public RegisterBindingModel RegisterBindingModel
{
get
{
return this._registerBindingModel;
}
set{
SetProperty(ref this._registerBindingModel, value);
}
}
public RegisterViewModel(INavigationService navigationService)
{
//...
this.RegisterBindingModel = new RegisterBindingModel();
}
}