close
在 Caliburn.Mico 中要設定 User Control 的 view model,有以下兩種方式:
<local:MyUserControl caliburn:Bind.Model="{Binding Model}"/> <local:MyUserControl caliburn:Bind.Model="CaliburnDemoApp2.MyUserControlViewModel"/>
第一種是在 page 的 view model 裡,宣告一個屬性給 User Control,第二兩種是直接指定型別給 User Control。第一種的好處在於可以控制 User Control 的資料,第二種則是讓 page 裡的 view model 跟 User Control 切開關係。
而第一種方式,在產生 User Control 所需的 View Model 時,通常使用下列方法:
this.Model = IoC.Get<MyUserControlViewModel>();
但記得,透過 Ioc 取得物件時,必需事先註冊該型別。註冊型別時,可以用這樣自動化的方式進行:
Assembly assembly = this.GetType().GetTypeInfo().Assembly; Type viewModelBaseType = typeof(ViewModelBase); Type screenType = typeof(Screen); //load ViewModel type that inherited ViewModelBase or Screen var types = from modelType in assembly.GetExportedTypes() where modelType.GetTypeInfo().BaseType == viewModelBaseType || modelType.GetTypeInfo().BaseType == screenType select modelType; foreach (var type in types) { System.Diagnostics.Debug.WriteLine("Registerd ViewModel:{0}", type); _container.RegisterPerRequest(type, type.FullName, type); }
有了這樣的觀念,相信在使用 User Control 時就不會有太大的挫折。
全站熱搜