What?
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)
How?
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.
Behavior:
public class UnhandleKeyDownBehavior : Behavior { private KeyEventHandler _handler; protected override void OnAttached() { base.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() { base.OnDetaching(); AssociatedObject.RemoveHandler(UIElement.KeyDownEvent, _handler); } public Key Key { get; set; } } }
Comments