新建一個WPF項目,將其命名為Caliburn.Micro.BindingsDemo 其次安裝Caliburn.Micro,安裝Caliburn.Micro的同時也會安裝Caliburn.Micro.Core 然後新建Views文件夾和ViewsModels文件夾,前者是放視圖的,後者是放管理視圖的 ...
新建一個WPF項目,將其命名為Caliburn.Micro.BindingsDemo
其次安裝Caliburn.Micro,安裝Caliburn.Micro的同時也會安裝Caliburn.Micro.Core
然後新建Views文件夾和ViewsModels文件夾,前者是放視圖的,後者是放管理視圖的VM
然後刪掉MainWindow.xaml,是的就是刪掉它,再刪掉app.xaml裡面的uri的引導頁面,然後添加引導頁面代碼,如下
<Application.Resources> <ResourceDictionary> <ResourceDictionary.MergedDictionaries> <ResourceDictionary> <local:Bootstrapper x:Key="Bootstrapper" /> </ResourceDictionary> </ResourceDictionary.MergedDictionaries> </ResourceDictionary> </Application.Resources>
然後添加類,命名為Bootstrapper,這個就是起到引導作用,放到根目錄下,起到復用的作用,如下
在OnStartup中就是重寫了引導頁面的作用,引導的頁面為ShellView。
Bootstrapper的代碼如下
public class Bootstrapper : BootstrapperBase { private SimpleContainer container; public Bootstrapper() { Initialize(); } protected override void Configure() { container = new SimpleContainer(); container.Singleton<IWindowManager, WindowManager>(); container.PerRequest<ShellViewModel>(); } protected override void OnStartup(object sender, StartupEventArgs e) { DisplayRootViewFor<ShellViewModel>(); } protected override object GetInstance(Type service, string key) { return base.GetInstance(service, key); } protected override IEnumerable<object> GetAllInstances(Type service) { return base.GetAllInstances(service); } protected override void BuildUp(object instance) { container.BuildUp(instance); } }
其次在ViewModels中分別新建ActivityBaseViewModel,MessageActivityViewModel,PhotoActivityViewModel,ShellViewModel這四個類
ShellViewModel的代碼如下
public class ShellViewModel : Screen { private ActivityBaseViewModel selectedActivity; public ShellViewModel() { Activities = new BindableCollection<ActivityBaseViewModel> { new MessageActivityViewModel("MessageOne"), new PhotoActivityViewModel("PhoneOne"), new MessageActivityViewModel("MessageTwo"), new PhotoActivityViewModel("PhoneTwo") }; } public BindableCollection<ActivityBaseViewModel> Activities { get; } public ActivityBaseViewModel SelectedActivity { get { return selectedActivity; } set { Set(ref selectedActivity, value); } } }
緊接著往Views文件建視圖,分別建MessageActivityView,PhotoActivityView,ShellView,三個視圖,其中ShellView用Windows窗體級別,而MessageActivityView和PhotoActivityView都是UserControl級別,因為Page放不到Windows窗體中。
MessageActivityView視圖如下
PhotoActivityView視圖如下
ShellView視圖如下
整個邏輯是這樣,先把資源綁定到UserControl中,然後再把UserControl視圖綁定到ShellView視圖中,因為ShellView的視圖級別是Windows的,所以是可以放UserControl。所以理一下,這篇文章講的是綁定bindings,整個邏輯是非常的清晰的。所以看下運行後的結果
文章僅供學習參考,如有不對,請多多指教,謝謝各位看官。