Caliburn Micro #003 : Events (Short Hand Syntax)

Previously, We looked at one approach of binding Events to Controls. However, the convention based approach is one of the least used approaches in Caliburn Micro. Think about it, if you need to bind more than one event to the control, say for example, the Click Event and MouseOver Event, this approach would fall short.
Thankfully, Caliburn Micro provides another approach, based on Event Triggers, which solves this problem. While there is a long annotation version of the approach, we would stick to the shorthand version, which is, designed to be more developer friendly.
Convention Based Approach
Let’s declare a button and assign a OnClick Event to the control using the convention based approach first.
 <Button  x:Name="ClearTextMethod">Clear</Button>

Now, Let’s change the signature to Event Trigger based approach. First, we need to add a namespace in our XAML Headers.


Event Trigger Based Approach
And now we will attach the event. Notice the change in Syntax.

<Button Content="Clear" cal:Message.Attach="[Event Click] = [Action ClearTextMethod]" />

As mentioned earlier, this approach allows us to attach more events to the Control. If we need to attach a MouseOver Event to the above button, all we need to do is add another pair of [Event][Action] separated by a semi-colon

<Button Content="Clear" cal:Message.Attach="[Event Click] = [Action ClearTextMethod];[Event MouseLeave]=[Action AnotherMethod]" />

Passing Parameter

We could also pass parameters to the method, with the same syntax.

A word of caution though when you pass a boolean parameter to the method. For example, invoking the method with following syntax doesn’t quite work.

<Button Content="Clear" cal:Message.Attach="[Event Click] = [Action ClearTextMethod(true)]" />

The workaround is fairly simple thought, just include a single quote around the string representing True/False. We can modify the syntax as following.

<Button Content="Clear" cal:Message.Attach="[Event Click] = [Action ClearTextMethod('true')]" />

Complete list of tutorials on Caliburn.Micro can be found here


3 thoughts on “Caliburn Micro #003 : Events (Short Hand Syntax)

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s