Sony Arouje

a programmer's log

Posts Tagged ‘Event Aggregator

An Introduction to Caliburn Micro

with 22 comments

 
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.

Written by Sony Arouje

November 7, 2010 at 11:05 pm

%d bloggers like this: