Skip to content →

Unhandling previously handled events in Silverlight


You may well find yourself wanting to attach to an event which has already been handled inside a control with no way to override and prevent the event from being handled. As seen in my prior post to this, you can make use of the AddHandler method. I am going to use the Backspace key down in a TextBox as an example, the event is only raised and not handled when the TextBox is empty. (This can be seen in the sample application in the output coming from the behavior)


I have created a behavior which “unhandles” a key down and executes a command when the event is raised (Note: there is no need to attach to the event on the textbox as well). To prove this, in the examples output you can see the key down and key up events being raised as well as the behavior being executed on backspace.


public class UnhandleKeyDownBehavior : Behavior
    private KeyEventHandler _handler;

    protected override void OnAttached()
        _handler = new KeyEventHandler(AssociatedObjectKeyUp);
        AssociatedObject.AddHandler(UIElement.KeyDownEvent, _handler, true);

    private void AssociatedObjectKeyUp(object sender, KeyEventArgs e)
        if (e.Key == Key)
            e.Handled = false;

    protected override void OnDetaching()
        AssociatedObject.RemoveHandler(UIElement.KeyDownEvent, _handler);

    public Key Key { get; set; }



Sample App

Install Microsoft Silverlight

Published in Development


Leave a Reply

Your email address will not be published. Required fields are marked *


This site uses Akismet to reduce spam. Learn how your comment data is processed.