Caliburn Micro Part 2: Data Binding and Events

In my previous blog post I showed you how to get started with using the Caliburn Micro Framework in a WPF application. Caliburn Micro helps us implement the application using the MVVM design pattern to get a clean separation between the view and the data model. In this blog post we’ll take a look at how Caliburn Micro assists us with data binding and events. We will be building on top of the application outlined in the previous blog post to add some simple user interaction and data display.

Data binding

We’ll start by getting the application to display a numerical value that is stored in the model. In the AppViewModel class created in the previous blog post, add a property called Count as seen in the code snippet below. The property value is stored in the _count field which we have given a default value of 50. You may recall from last time that we made the AppViewModel class extend the PropertyChangedBase provided by Caliburn Micro to preform property change notifications. Rather than implementing INotifyPropertyChanged in all of your models, you can simply call the NotifyOfPropertyChange method within the setter of your properties.

public class AppViewModel : PropertyChangedBase
{
  private int _count = 50;
 
  public int Count
  {
    get { return _count; }
    set
    {
      _count = value;
      NotifyOfPropertyChange(() => Count);
    }
  }
}

Next we modify the view to display this property value. In AppView.xaml, add a TextBox to the grid as follows:

<Grid MinWidth="300" MinHeight="300" Background="LightBlue">
  <TextBlock Name="Count" Margin="20" FontSize="150" VerticalAlignment="Center" HorizontalAlignment="Center" />
</Grid>

Now run up the application and see that the TextBlock is displaying the default value of the Count property.

A Caliburn Micro app displaying some data

Wait… what? I don’t remember setting any binding on the TextBlock to get the Count property, and yet the TextBlock is displaying the correct data!

Notice that I’ve set the name of the TextBlock to be the same as the property we want to bind to. This is a convenient short cut that Caliburn Micro provides. For elements that display data such as TextBlock or TextBox, setting their name to match a property on the data model will automatically hook it up for you.

Handling events

Next, let’s work on adding a button that increments the displayed value. The quick and dirty way of doing this is to hook up the Click event of a button to an event handler in the code behind. However, when using the MVVM pattern it’s usually best (but not absolutely necessary) to avoid using the code behind where you can. So let’s look at how to handle the events Caliburn Micro style. First, add a method to the AppViewModel for incrementing the Count property like this:

public void IncrementCount()
{
  Count++;
}

Now add a button to the grid in AppView.xaml as follows:

<Grid MinWidth="300" MinHeight="300" Background="LightBlue">
  <RepeatButton Name="IncrementCount" Content="Up" Margin="15" VerticalAlignment="Top" />
  <TextBlock Name="Count" FontSize="150" VerticalAlignment="Center" HorizontalAlignment="Center" />
</Grid>

Running the application now and clicking the button will increment the count value as advertised. Once again you’ll notice that we don’t need to do much work to hook the click event of the button to the IncrementCount method. For certain user interface controls such as buttons, you can simply set the name of the control to be the name of the method you want it to be hooked to. Caliburn Micro will hook the appropriate event of the user control to the specified method in the model. In the case of buttons, Caliburn Micro deals with the Click event. (You can also manually specifying which event to hook up to which method which we’ll look at next time).

Clicking the button increments the value

Event guards

When Caliburn Micro automatically hooks up the Click event to the IncrementCount method, it also looks for a method or property called CanIncrementCount. By adding a CanIncrementCount method or property, you can include additional logic that determines whether the event is allowed to be handled based on the current state of the model. Let’s do this now by adding the following property to the AppViewModel:

public bool CanIncrementCount
{
  get { return Count < 100; }
}

Since this logic is based on the value of the Count property, we also need to raise property change notification for the CanIncrementCount property whenever the Count value changes. This is done by adding this line of code on the Count property setter:

NotifyOfPropertyChange(() => CanIncrementCount);

Run up the application once more and increment the value to 100. Once the limit has been reached, the button will become disabled and prevent the user from further incrementing the value.

Button is disabled when count is 100

In this tutorial we have looked at a few ways that Caliburn Micro takes some of the work off our shoulders. Now you can more quickly use data binding, property change notifications, event handlers and event guards, while at the same time implementing a sturdy MVVM application that is easier to test and maintain.

You can download the full Visual Studio 2010 solution for this tutorial here. Use it to practice your new skills by adding a button to decrement the value.

In the next instalment of this blog series, we’ll take a look at more advanced scenarios of event handling with Caliburn Micro, specifically with passing event parameters. See you then.

Tagged as General, WPF

10 Responses to “Caliburn Micro Part 2: Data Binding and Events”

  • Cool tutorial. Look forward to learning more about Caliburn Micro.

  • Hello Jason. Thanks so much for explaining Caliburn Micro. I have been following along since part 1 and its well written. The official docs is not aimed at the very beginner imo.

  • I’ve been struggling with MVVM and Caliburn Micro, great beginners guide.
    Thanks

  • Yep, excellent articles on Caliburn Micro

  • [...] 1: Getting Started Part 2: Data Binding and Events Part 3: More About Events and Parameters Part 4: The Event [...]

  • [...] the next part of this blog series we will look at adding some interactivity using events and data binding with the help of Caliburn [...]

  • hi,
    thanks for creating this excellent and easy to follow tutorial… Caliburn Micro appears to be a fantastic framework.
    looking forward to building some prototype apps with it..

  • Hi Jason. First of all, thank you for your tutorial.
    I want to know follow :
    If the “Count” element in the AppView is a TextBox Control, when i change the Count’s Value, How I do custom behavior, such as update the DataBase?

    How?

  • Hello zm.lee

    This partly depends on the database operation you want to do. If it is a heavy operation, you probably don’t want it to occur every time the user types to change the value. In this case you would either want to include a button for the user to press that executes the operation, or at least use a binding on the TextBox with UpdateSourceTrigger=LostFocus so that the operation only occurs when the user is done changing the value. If it is a simple operation which is fine to occur often as the user is changing the value, then you can just include a property in the view-model with the same Name as the TextBox and Caliburn micro will use a TwoWay binding to connect them.

    Once you’ve sorted out how to link the view-model to the TextBox, you can then use the users value to perform your database operation. If you manage the database in a different view-model than the one that links to the TextBox, then you’ll want to raise an event from the text box view-model to be caught by the database view-model which can then perform the operation. Tutorial 4 talks about the Event Aggregator which can be used to send event messages between the various view-models of your application.

    Hope that helps

    -Jason

  • These Caliburn.Micro tutorials are awesome, as someone who is relatively new to WPF, I am very appreciative.

    Thank you.

  • Leave a Reply

Archives

Join our mailer

You should join our newsletter! Sent monthly:

Back to Top