Skip to main content

Events

Class handlers

In WPF, class handlers for events can be added by calling EventManager.RegisterClassHandler. An example of registering a class handler in WPF might be:

WPF
static MyControl()
{
EventManager.RegisterClassHandler(typeof(MyControl), MyEvent, HandleMyEvent));
}

private static void HandleMyEvent(object sender, RoutedEventArgs e)
{
}
Avalonia
static MyControl()
{
MyEvent.AddClassHandler<MyControl>((x, e) => x.HandleMyEvent(e));
}

private void HandleMyEvent(RoutedEventArgs e)
{
}

Notice that in WPF you have to add the class handler as a static method, whereas in Avalonia the class handler is not static: the notification is automatically directed to the correct instance. The sender parameter typical of event handlers is not necessary in this case and everything remains strongly typed.

Tunnelling events

Avalonia has tunnelling events but they're not exposed via separate Preview CLR event handlers. To subscribe to a tunnelling event you must call AddHandler with RoutingStrategies.Tunnel:

target.AddHandler(InputElement.KeyDownEvent, OnPreviewKeyDown, RoutingStrategies.Tunnel);

void OnPreviewKeyDown(object sender, KeyEventArgs e)
{
// Handler code
}

A cross-platform WPF.

Experience your WPF app on macOS, Linux, Mobile & Web

Discussion

Have questions or feedback? Join the conversation below.