Search
Tutorial 4: Handling events in XML

This tutorial extends the Custom composite node tutorial by adding event handling to the XML component definition.

1. Modifying the XML definition

The first step is to modify the XML component definition from the previous example to include event handlers. For the purposes of this tutorial we will add a handler to the Clicked event of the ImageComponent. Modify the definition of the image component in the XML as illustrated below:

C#  Copy Code

...
<Image Name=""Image"" ImageAlign=""Fit"" Clicked=""OnImageClicked"" IsInteractive=""True"" />
...

Visual Basic  Copy Code

...
"      <Image Name=""Image"" ImageAlign=""Fit"" Clicked=""OnImageClicked"" IsInteractive=""True"" />" & _
...

Note, that in addition to the event handling we are also setting IsInteractive to true. By default image components cannot be interacted with and if this property is not set, the event will not be raised.

2. Defining the event handler

Add an event handler with a matching prototype to the OrgChartNode class. If no matching method is found when the XML is loaded, the loader will throw an exception.

C#  Copy Code

private void OnImageClicked(object sender, EventArgs e)
{
    MessageBox.Show("The image was clicked.");
}

Visual Basic  Copy Code

Private Sub OnImageClicked(ByVal sender As Object, ByVal e As EventArgs)

    MessageBox.Show("The image was clicked.")

End Sub

The above handler merely displays a message box in response to a click on the image.

3. Providing event handler target

The last step is to supply to the XmlLoader a reference to the object handling the event. In this case this is the current object, but this is not obligatory. To specify the event handler target, pass a reference as an argument to the appropriate Load method.

C#  Copy Code

Components.Add(XmlLoader.Load(content, this, null));

Visual Basic  Copy Code

Components.Add(XmlLoader.Load(content, Me, Nothing))

Note that instead of passing null (Nothing in Visual Basic) as the second argument of the Load method we are passing a reference to the current object. If no event handler target is provided loading the XML will fail with an exception.