【发布时间】:2017-04-12 10:49:10
【问题描述】:
我正在尝试在我的 xamarin 移动项目中实现 MVVM 模式。
我有以下 MVVM 文件
- 登录查看
- LoginViewModel
- BaseViewModel
以下是我的LoginViewModel
public class LoginViewModel : BaseViewModel
{
private bool isLoginIndicator= false;
private string etUserName;
private string etPassword;
public LoginViewModel()
{
OnLogin = new Command(doLogin , ()=>!LoginIndicator);
MessagingCenter.Subscribe<IMessage, EventType>(this, RestApi.UI_EVENT, (sender, eventType) =>
{
LoginIndicator = false;
if (eventType.status)
{
Application.Current.MainPage.DisplayAlert(AppResources.success, "Login done", "Ok");
}
else
{
Application.Current.MainPage.DisplayAlert(AppResources.failed, eventType.errorMessage, "Ok");
}
});
}
public bool LoginIndicator
{
get { return isLoginIndicator; }
set
{
isLoginIndicator = value;
OnPropertyChanged("LoginIndicator");
OnLogin.ChangeCanExecute();
}
}
public string UserName
{
get { return etUserName; }
set
{
etUserName = value;
OnPropertyChanged("UserName");
}
}
public string Password
{
get { return etPassword; }
set
{
etPassword = value;
OnPropertyChanged("Password");
}
}
public Command OnLogin { get; }
void doLogin()
{
LoginIndicator = true;
UserRequest user = new UserRequest();
user.userName = etUserName;
user.password = etPassword;
user.companyId = "CEE";
user.appVersion = Constants.getAppVersion();
user.osVersion = Constants.getOSVersion();
user.deviceId = Constants.getDeviceModel() + " " + Constants.getDevicePlatform();
new RestApi().userLogin(JsonConvert.SerializeObject(user));
}
}
当 OnLogin 命令从 Button 被触发并使用 MessageCenter 广播 Message 时,此类通常会进行 Web 服务调用
现在我想导航到我的MainPage,这是用户成功登录后的母版页,因此当eventType.status 在Message Subscriber 中为真时,我需要导航到母版页
但我不知道如何根据 MVVM 模式正确导航到其他页面。
我尝试在网上搜索,发现有现成的框架可用,如MVVMCross 和MVVMLight 等。但我不想使用这些依赖项,如果有人可以建议,我愿意以其他方式实现导航
【问题讨论】:
-
Application.Current.MainPage = new MyFirstPageAfterLogin();不正确?
-
这会是在 MVVM 模式中执行此操作的正确方法吗?不过不确定:)
-
我不知道...我认为您应该将 MessagingCenter 从 ViewModel 发送到 View 并在 View 中使用 Application.Current.MainPage = new... 但我不确定。我不是很了解 MVVM...
标签: xamarin mvvm xamarin.forms