MvvmCross覆盖Android的viewmodel关联

时间:2013-09-21 14:17:14

标签: android viewmodel mvvmcross

我试图覆盖默认的视图模型关联但到目前为止没有运气。我需要覆盖此默认行为,因为我的某些ViewModel不遵循默认视图模型查找所假定的名称约定。例如,我在命名空间Pidac.Core.ViewModels中有一些ViewModel,而视图在MyApplication.Droid.Views中定义。

我尝试过在Droid项目的Setup.cs中提供明确类型映射的选项,如下所示:

 protected override void InitializeViewLookup()
        {
            var viewModelViewLookup = new Dictionary<Type, Type>()
            {
                  { typeof (FirstViewModel), typeof(FirstView) },     
                  { typeof (FloatSettingViewModel), typeof(FloatSettingView) },
                  { typeof (SettingsViewModel), typeof(SettingsView) },
                  { typeof (SearchResultDialogViewModel), typeof(SearchResultDialogView) },
            };

            var container = Mvx.Resolve<IMvxViewsContainer>();
            container.AddAll(viewModelViewLookup);      
        }

有了这个,我的应用程序不再通过MvvmCross徽标屏幕。

或者,我尝试在FloatSettingView.cs中提供具体的视图模型类型,如下所示:

[Activity(Label = "settings", Theme = "@android:style/Theme.NoTitleBar")]
    public class FloatSettingView : MvxActivity
    {
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);
            SetContentView(Resource.Layout.FloatSettingView);
        }

        public new FloatSettingViewModel ViewModel
        {
            get { return base.ViewModel as FloatSettingViewModel; }
            set { base.ViewModel = value; }
        }
    }

仅使用第二种方法,没有提供视图模型来查看Setup.cs中的类型映射,当框架尝试加载FloatSettingView时,我得到一个异常。例外是Failed to find viewmodel for Pidac.Core.ViewModels.FloatSettingViewModel.

我尝试使用MvxViewForAttribute修改我的视图的第三个选项如下:

 [Activity(Label = "settings", Theme = "@android:style/Theme.NoTitleBar")]
[MvxViewFor(typeof(FloatSettingViewModel))]
        public class FloatSettingView : MvxActivity
        {
            protected override void OnCreate(Bundle bundle)
            {
                base.OnCreate(bundle);
                SetContentView(Resource.Layout.FloatSettingView);
            } 

        }
没有运气。我显然在这里忽略了一些东西。在我深入研究资料来源之前,有没有人这样做过?

TIA。

1 个答案:

答案 0 :(得分:0)

您应该在覆盖时致电base.InitializeViewLookup(),这样您才能越过启动屏幕。