AWG Blogs

Friday, February 15, 2013

Bind ViewModel Declaratively with Caliburn.Micro in Non-Caliburn.Micro App

I have an existing Silverlight App with Frame based navigation and the app is fairly stable. I wanted to look into logging interception of ViewModels and that is when I started testing Caliburn.Micro (per an answer to my question here). My aim is to gradually migrate pages over to the Caliburn.Micro framework, but not have CM take over the App at first (i.e. set the RootVisual). The closes discussion on the web I could find regarding this scenario was http://caliburnmicro.codeplex.com/discussions/260738. To do a proof-of-concept I simply combined the files from the Caliburn.Micro.ViewFirst sample project with a SL Nav template project:

- Create a new "Silverlight Navigation Application" project
-Add existing files from ViewFirst sample: IShell.cs, MefBootstrapper.cs, and ShellViewModel.cs (change namespaces if desired)
- Add necessary references to MEF and Caliburn.Micro
- In MefBootstrapper, remove the OnStartup override method, since we are not setting the rootvisual, but instead letting the App.xaml do that. Note I thought it was necessary to also override the constructor and set "base(false)" but it seems to work either way, so I left it out.
- Copy the StackPanel element and its content from ShellView.xaml into the ContentStackPanel of About.xaml
- For the declarative binding of VM, also add the following also to About.xaml:     cal:Bind.Model="Shell"  xmlns:cal="http://www.caliburnproject.org"
- At the top of the App constructor of App.xaml.cs add:             new MefBootstrapper();
- Press F5, click "About" and notice that you have a working Caliburn.Micro ViewModel View with Actions all wired up automatically!