为同一ViewModel绑定两个不同的视图 [英] Bind Two Different Views for same ViewModel
问题描述
这看起来类似于 MVVMCross-将相同的ViewModel绑定到2个不同的视图
但是在那之后我没有得到答案,如何为ViewModel选择一个视图,而在另一时间为同一ViewModel选择第二个视图.
But after there I don't get an answer how can I select one View for ViewModel and in another time the second View for the same ViewModel.
作为一个例子,我想要一个ViewModel- LoginViewModel
和两个视图: PhoneLoginPage
& TabletLoginPage
.
As an example, I wanna have one ViewModel - LoginViewModel
and two Views: PhoneLoginPage
& TabletLoginPage
.
根据来自 Xamarin.Forms.Device.Idiom
的信息,当它是一部电话时,我想显示 PhoneLoginPage
,但是当它是平板电脑时- TabletLoginPage
,但绑定了相同的 LoginViewModel
.
According to information from Xamarin.Forms.Device.Idiom
when it's a Phone I want to show PhoneLoginPage
but when it's a Tablet - TabletLoginPage
but have the same LoginViewModel
binded to them.
如何正确实现?意思是,没有任何肮脏的把戏...
How can I achieve it correctly? Mean, without any dirty tricks...
谢谢
推荐答案
使用MvvmCross是不可能的,在运行时,如果我们为同一个ViewModel创建两个视图,则将获得异常.
With MvvmCross this is not possible, in runtime, we will get an Exception if we create two Views for the same ViewModel.
下一个是我的解决方法:
My solution was next:
<ProjectFolder>
=> Pages
=> Mobile
XMobilePage.xaml
YMobilePage.xaml
=> Tablets
XTabletPage.xaml
YTabletPage.xaml
=> PageModels
=> Mobile
XMobilePageModel.cs
YMobilePageModel.cs
=> Tablets
XTabletPageModel.cs
YTabletPageModel.cs
class XMobilePage: MvxContentPage<XMobilePageModel> {...}
class XTabletPage: MvxContentPage<XTabletPageModel> {...}
abstract SharedXPageModel
{
//All Shared Commands and Comand Logic and other shared initialization
abstract Task NavigateToYPageModel();
}
class XMobilePageModel : SharedXPageModel
{
Task NavigateToYPageModel() => _mvxNavigationService.Navigate<YMobilePageModel>();
}
class XTabletPageModel : SharedXPageModel
{
Task NavigateToYPageModel() => _mvxNavigationService.Navigate<YTabletPageModel>();
}
这篇关于为同一ViewModel绑定两个不同的视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!