Silverlight’s KeyUp Event and Backspace

Surprisingly enough, I never ran into this issue, event though I worked with Silverlight for three years now.  The specific issue is that some keyboard events are not echoed in KeyUp events.  For example, if you subscribe to KeyUp in a textbox and you hit Backspace key, KeyUp event does not fire.  This is quite inconsistent in my opinion.  The reason this happens is because the event is trapped by Silverlight, processed independently and marked as Handled, so it does not bubble up to the textbox.  You can see some workarounds on the internet, most involving inheriting from a textbox.  I do not particularly like this answer because it involves a lot of work on my part.

So, I wanted to blog about functionality in Silverlight that is not widely known, but I used on a few occasions.  Specifically, it allows developers to receive events that have been marked as handled elsewhere.

I am referring to AddHandler function.  Here is typical syntax:

Element.AddHandler(UIElement.KeyDownEvent, new KeyEventHandler(Element_KeyDown), true);

Element.AddHandler(UIElement.KeyDownEvent, new KeyEventHandler(Element_KeyUp), true);

The key is the last parameter to AddHandler.  It signals to Silverlight to inform you of the events even though they have been marked as handled.  You would use this call instead of

Element.KeyUp += Element_KeyUp;

You can read more about this function here.

Enjoy.

Thanks.

Leave a Reply

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