Intersoft ClientUI Documentation
How to: Add Class Handling for a Routed Event

Routed events can be handled either by class handlers or instance handlers on any given node in the route. Class handlers are invoked first, and can be used by class implementations to suppress events from instance handling or introduce other event specific behaviors on events that are owned by base classes.

This example illustrates how to implement class handlers using code.

Example

Description

One of the most common scenarios in working with a routed event is to use class handlers to handle multiple instances of objects in certain node of the visual tree which type is already known to be traversed by the routed event.

For instance, consider a registration form where your application is responding as user types into textbox or changes selection in combobox. Instead of handling each textbox independently, you can write a class event handler that will be invoked when any of the textbox instances raise the routed event.

The following example shows how to write class handler for efficient routed event handling.

Code

C#
Copy Code
static Default()
{
    // register class-level routed event handler
    // this enables the event of all instances with the same type to be handled at once
    EventManager.RegisterClassHandler(typeof(Default), Keyboard.KeyUpEvent, new KeyEventHandler(OnKeyUp), true);
    EventManager.RegisterClassHandler(typeof(Default), UXComboBox.SelectionChangedEvent, new SelectionChangedEventHandler(OnSelectionChanged));
    EventManager.RegisterClassHandler(typeof(Default), UXCheckBox.CheckedStateChangedEvent, new ISRoutedEventHandler(OnIsCheckedChanged));
}

private static void OnSelectionChanged(object sender, SelectionChangedEventArgs e)
{
    Default page = sender as Default;
    page.SetEventStatus("ComboBox selection changed...");

    e.Handled = true;
}

private static void OnIsCheckedChanged(object sender, ISRoutedEventArgs e)
{
    Default page = sender as Default;
    page.SetEventStatus("CheckBox check state changed...");

    e.Handled = true;
}

private static void OnKeyUp(object sender, KeyEventArgs e)
{
    if (e.OriginalSource is ISButton || e.OriginalSource is ISTextBox || e.OriginalSource is ISSelectionControl)
    {
        Default page = sender as Default;

        if (!e.Handled && KeyStroke.IsCharacter(e.Key) || KeyStroke.IsNumeric(e.Key))
        {
            page.SetEventStatus("Typing...");
            e.Handled = true;
        }
    }
}

private void SetEventStatus(string status)
{
    EventStatus.Text = status;

    // reset status in 1s
    Utility.ExecuteTimeOut(1,
        () =>
        {
            EventStatus.Text = "Idle";
        });
}

The sample code for this example can be found in the Handling Routed Events with Class Handler. For more information about the location of the sample, see Locating the Samples in Local Installation

See Also

Concepts

Other Resources