An Introduction to Caliburn Micro
Introduction
This post gives some brief introduction to develop Silverlight applications using Caliburn Micro which gives the basic features are:
- BootStrapping
- Conventions to write ViewModels
- Event Aggregation
- Action Message
Once you got the above basic ideas, it’s very easy to develop scalable applications in Silverlight. You can download the latest Caliburn Micro source from CodePlex.
When MVVM pattern introduced into my Silverlight development, initially it’s not digesting for me. But after I got the clear picture of MVVM pattern, I felt It’s very easy to develop Silverlight application that can adaptable to changes very easily. We choose Caliburn Micro as our MVVM framework, one reason it’s very light weight, another reason is the code base is very less. As the code base is very less we can go through it understand it better.
I hope every one who reads this post has some idea of MVVM pattern. In short MVVM separates View (presentation) and the code manipulates the view separately, and called it as View Model. One of the main advantage of MVVM is we can modify View or ViewModel without affecting each other. There is no event handlers for any control in the code behind, so it’s easy to replace one control with another. We can even reuse the same view model for different platform, let say we are developing an app for both Silverlight and WP7, here only difference in view is it’s base classes but UI is same. So we can share the same View Model thus by increase the maintainability and decrease the effort.
How the View and View Model’s will communicate? here the MVVM framework like Caliburn Micro will comes into picture. The MVVM Framework will bind the View and View Model’s. There are several MVVM frameworks in the market like Prism, MVVM Light, etc. but am not going to cover those.
Caliburn Micro uses conventions to bind View and View Model’s, I feel the conventions are better than wiring through code or attributes. You will get the conventions of Caliburn Micro as we progress through this post.
There are two approach in MVVM model, Code first and View first. Which one is better? I am not the person to comment on, their is an age old debate is going on. Personally I prefer Code First approach. But here to simplify things I will do it in View First approach.
Caliburn Micro In Action
Let’s do some small application in Silverlight using Caliburn Micro. The functionality of this app is pretty simple, display a list of customer and allow the user to edit it.
I am going to create a user control to display the details of individual customer. In the listing page we will bind this User control to a List. Let’s create the control.
IndividualResultView.xaml
<Grid x:Name="LayoutRoot" Background="White"> <Border BorderThickness="3" BorderBrush="Black" Margin="3"> <Grid Margin="5"> <Grid.RowDefinitions> <RowDefinition Height="30"></RowDefinition> <RowDefinition Height="60"></RowDefinition> <RowDefinition Height="30"></RowDefinition> <RowDefinition></RowDefinition> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition Width="120"></ColumnDefinition> <ColumnDefinition></ColumnDefinition> </Grid.ColumnDefinitions> <TextBlock x:Name="lblName" Text="Name" Grid.Row="0" Grid.Column="0"></TextBlock> <TextBlock x:Name="Name" Grid.Row="0" Grid.Column="1"></TextBlock> <TextBlock x:Name="lblAddress" Text="Address" Grid.Row="1" Grid.Column="0" ></TextBlock> <TextBlock x:Name="Address" Grid.Row="1" Grid.Column="1"></TextBlock> <TextBlock x:Name="lblPhoneNumber" Text="Phone#" Grid.Row="2" Grid.Column="0"></TextBlock> <TextBlock x:Name="PhoneNumber" Grid.Row="2" Grid.Column="1"></TextBlock> <HyperlinkButton x:Name="EditCustomer" Grid.Row="3" Content="Edit"></HyperlinkButton> </Grid> </Border> </Grid>
IndividualResultView.xaml.cs
Let’s see the IndividualResultView.xaml.cs, as per the MVVM pattern it should not contain any View related code, other than initializing the UI controls. You can see that our code behind is clean.
using System.Windows.Controls; namespace WCFEnabledSilverlightApp.Views { public partial class IndividualResultView : UserControl { public IndividualResultView() { InitializeComponent(); } } }
We need to create a ViewModel for the above view, let’s do it. I named my ViewModel as IndividualResultViewModel.cs. Below is the code
using DataModel; using Caliburn.Micro; namespace WCFEnabledSilverlightApp.ViewModels { public class IndividualResultViewModel:PropertyChangedBase { string _name; public string Name { get { return _name; } private set { _name = value; NotifyOfPropertyChange(() => Name); } } string _address; public string Address { get { return _address; } private set { _address = value; NotifyOfPropertyChange(() => Address); } } public string PhoneNumber { get; private set; } private Customer _customer = null; public IndividualResultViewModel(Customer customer) { this._customer = customer; this.Name = customer.CustomerName; this.Address = customer.Address; this.PhoneNumber = customer.PhoneNumber; } public void EditCustomer() { EditCustomerViewModel editCustomer = new EditCustomerViewModel(_customer); Screen scrn = new Screen(); WindowManager winMngr = new WindowManager(); winMngr.ShowDialog(editCustomer); } } }
Convention 1
We learned our first convention of Caliburn Micro. The UI should suffix with “View”. The View Model should suffix with “ViewModel” and prefix with ViewName
<ViewName>View.xaml
<ViewName>ViewModel.cs
Eg.
IndividualResultView.xaml
IndividualResultViewModel.cs
Convention 2
You might have noticed that in the view and viewmodel we used some convention. The name of TextBlock that display the customer details have a corresponding property in ViewModel. For E.g. the TextBlock name for displaying Customer Name is “Name” and in ViewModel you can see a property “Name”. The Caliburn Micro will bind the Property in the ViewModel to the View. That means what ever value we set for property “Name” will be displayed in the View. Pretty simple.
You might have one question now how to handle click event or those kind of events raised by your view in our View model. It’s pretty easy create a function with same name as your button. Just go back to the View and check the name of the hyperlink button, also check whether their is method with same name in View model. Hyperlink button name is EditCustomer and I have one method in View model EditCustomer. The method will create an instance of another view model.
Later in this post you can see how we can pass parameters from your view to view model.
NotifyOfPropertyChange
In our properties the setter calls a function called NotifyOfPropertyChange, what is the use of this function call? We call this function to notify the UI that the value has changed in the view model. We can notify UI without calling NotifyOfPropertyChange by implementing INotifyPropertyChanged interface and pass the property name. Caliburn Micro wraps the implementation of INotifyPropertyChanged in PropertyChangedBase and our view model is inherited from it. NotifyOfPropertyChange we are not passing any string value instead we pass the Property itself. The advantage of this method is we can use VS refactoring feature on properties. If we pass it as string then refactoring will not take into consideration.
Event Handling
When I implemented MVVM using Caliburn Micro I implemented the communication between View Models using normal event driven mechanism. That means If I want to handle an event occurred in a child view model in the parent. Then child view model raise an event and the parent will handle it. I didn’t like this approach as it creates a dependency between View models. So I start exploring Caliburn Micro to figure out the event handling features and my search ends in EventAggregator.
Caliburn Micro’s Event Aggregator functionality is a very powerful implementation of Observer pattern. We can write View Models with less coupling using EventAggregators. Let’s see how can we establish communication between View Models using Event Aggregator.
In the sample code I created a static property to give access to EventAggregator as shown below
public class EventAggregationProvider { static EventAggregator _eventAggregator = null; public static EventAggregator EventAggregator { get { if (_eventAggregator == null) _eventAggregator = new EventAggregator(); return _eventAggregator; } } }
In the sample app I have a popup window to edit the Customer Details, when the user clicks Save/Ok I need to notify the Parent View Model to initiate the Save process. Let’s see how to implement it.
In my CustomerEditViewModel.cs there is a method called SaveCustomer which will get called when the user clicks Ok from the View. You can see that in SaveCustomer I am publishing the Customer object. See how I am publishing it.
EventAggregationProvider.EventAggregator.Publish<Customer>(customer);
This ViewModel done his job, it’s job of the parent view model who can subscribe to this message and get the notification. Now let’s see how the parent view model is subscribing to this event.
public class CustomerListingViewModel : PropertyChangedBase, IHandle<Customer> {
public CustomerListingViewModel()
{
Messages.EventAggregationProvider.EventAggregator.Subscribe(this);
}
public void Handle(Customer message) { //do the save process }
}
To Subscribe to Customer message the CustomerListingViewModel is implemented by IHandle<Customer>. That means this CustomerListingViewModel is capable of handling any message with type Customer. One more line of code need to added to get notification. You can see in the constructor of CustomerListingViewModel to subscribe to EventAggregator.
Your View Model can subscribe to any number of messages by implementing IHandle with the respective type. For e.g
public class CustomerListingViewModel : PropertyChangedBase, IHandle<Customer>,IHandle<Order> {
public CustomerListingViewModel()
{
Messages.EventAggregationProvider.EventAggregator.Subscribe(this);
}
public void Handle(Customer message) { //do the save process }
public void Handle(Order message)
{
//do the save process
}
}
In the above e.g this View Model will get notified if any view model publish Customer or Order message.
Action Message
The Action Message is one of the functionality of Caliburn Micro to call parameterized function from View. Let’s see how we can do it. To do this we need to refer system.windows.interactivity assembly.
In the below e.g. a message box will show when a LostFocus happened in View EditCustomerView. Let’s go through the View
xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity" xmlns:ca="clr-namespace:Caliburn.Micro;assembly=Caliburn.Micro"
<TextBox x:Name="Name" Grid.Row="0" Grid.Column="1"> <i:Interaction.Triggers> <i:EventTrigger EventName="LostFocus"> <ca:ActionMessage MethodName="NameLostFocus"> <ca:Parameter Value="{Binding ElementName=Name,Path=Text}"></ca:Parameter> </ca:ActionMessage> </i:EventTrigger> </i:Interaction.Triggers> </TextBox>
I referenced System.Windows.Interactivity and Caliburn Micro in the View. As you can see in the above view I mentioned “LostFocus” to the EventName. The ActionMessage takes the MethodName that we created in the ViewModel. Parameter’s Value take the parameter to the method. So what’s this means, it’s very simple, whenever the lost focus happened in Name text box then the view should call NameLostFocus method with TextBox’s Text as the parameter. Below is the NameLostFocus method in the ViewModel
public void NameLostFocus(string text) { MessageBox.Show(text); }
You can see more about Action Message in Rob’s blog
Bootstrapping
Bootstrapping is the method of booting our application and allow Caliburn Micro to take the control. So how to create a bootsrapper. It’s very simple as shown below
namespace WCFEnabledSilverlightApp { public class BootStrapper:Bootstrapper<ViewModels.CustomerListingViewModel> { } }
It’s tells caliburn that CustomerListingViewModel is the first page to load. It’s same as setting RootVisual to the some page say MainPage in non MVVM model. We need to provide this BootStrapper in App.xaml as shown below
<Application xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" x:Class="WCFEnabledSilverlightApp.App" xmlns:bs="clr-namespace:WCFEnabledSilverlightApp" > <Application.Resources> <bs:BootStrapper x:Name="bootStrapper"></bs:BootStrapper> </Application.Resources> </Application>
Below is code behind of App.xaml. No code just clean.
using System.Windows; namespace WCFEnabledSilverlightApp { public partial class App : Application { public App() { InitializeComponent(); } } }
This post is just an introduction to Calibun Micro, just use it and get more comfortable with it. Thanks for reading this long post.
Introduction to Caliburn Micro Part 2
Download the source code.
[…] don’t think I need to explain Caliburn Micro in detail here. I wrote a post that gives a brief introduction to Caliburn […]
Photo Album using Silverlight, Caliburn Micro and Mongo DB | Sony Arouje Blog
November 16, 2010 at 1:18 am
Thanks for your article! Very nice intro. Although I’ve been working with CM for a while , it was still a great read!
Rybolt
November 17, 2010 at 8:38 pm
Thanks Rybolt for ur comment.
sonyarouje
November 17, 2010 at 9:46 pm
Thank you for very much for well written article.
arikhard
January 28, 2011 at 11:35 pm
[…] For more information about the EventAggregator look here. […]
Caliburn.Micro–Building an module-based application–Part I–The basement | Sliding Live
February 10, 2011 at 3:32 pm
[…] If you haven’t used Caliburn Micro please go through Caliburn Micro Introduction 1 […]
Introduction to Caliburn Micro – Part 2 | Sony Arouje Blog
February 16, 2011 at 2:51 pm
keep it up! Thanks
Ira Shikles
March 15, 2011 at 8:14 am
In your IndividualResultViewModel.EditCustomer(), I don’t see any usage of “Screen scrn = new Screen();”, is it a typo?
sun1991
May 27, 2011 at 7:40 pm
You are right, it’s actually a typo. Thanks for pointing the mistake. I removed it.
Sony Arouje
May 27, 2011 at 7:56 pm
[…] MvvM to use for my new WP7 Silverlight app and as usual there were a number of choices including Caliburn Micro, MvvM Light, Simple MvvM and Prism 4.0 for […]
Which MvvM for WP7? | Windows Phone 7 Blog
September 10, 2011 at 7:24 pm
Nice job, This is the best article about Caliburn Micro which I can find. Thanks.
lingate
October 4, 2011 at 9:13 am
Thanks Lingate, thanks for your feed back.
Sony Arouje
October 4, 2011 at 1:54 pm
I agree, this is the best and clean approach to CM. Sony is a communicator. I just need to know which Source file to download from Sky list. Anyone kknow?
Ben Hayat
October 8, 2011 at 7:00 pm
Ben thanks for ur feedback. All my uploads in skydrive is scrambled. All the links are pointing to one root folder. Right now on my way to India, I will update the post with the right file path once I reach home. Skydrive is driving me crazy. Sorry for the inconvience.
Sony Arouje
October 9, 2011 at 4:08 am
Ben you can download WCFEnabledSilverlightApp-CaliburnMicro.rar from the list..
Sony Arouje
October 9, 2011 at 4:18 am
Sony, my system would not allow me to download any of the files from any browser. Just would not get the Save dialog. I then connect to my machine at work and it complained that the files are “infected”. Just wanted to know that there are some infection in the files on your skydrive.
Hope this helps.
Ben Hayat
October 9, 2011 at 11:46 pm
Its very unfortunate to hear the file got infected in skydrive, I will verify it. I will send u the file in mail, eventually I move the all my files to some other place.
Sony Arouje
October 10, 2011 at 11:09 am
Here is the message I got:
FILE QUARANTINED
Microsoft Forefront Protection for Exchange Server removed a file since it was found to be infected.
File name: “WCFEnabledSilverlightApp-CaliburnMicro.rar”
Malware name: “ExceedinglyInfected”
Ben Hayat
October 10, 2011 at 5:13 pm
I will reupload it 2day.
Sony Arouje
October 11, 2011 at 7:40 am
That\’s a quick-witted aesnwr to a difficult question
Jose
November 18, 2012 at 7:35 am
I uploaded the files to Google docs. the new link is
Also the source code link in the post is also updated.
Sony Arouje
October 11, 2011 at 3:42 pm
[…] An Introduction to Caliburn Micro. […]
An Introduction to Caliburn Micro | Duong Tiet's blog
February 5, 2015 at 2:25 pm