views:

275

answers:

1

I have a PreviewKeyDown handler on my mainwindow which handles up and down keys so I can navigate with the keyboard between my controls.

Now I have the problem that in some Textboxes I also want to use the up/down keys. This seems impossible because the other handler seems to swallow the keys first.

Is it possible that when one of these TextBox controls are focused they get the up/down keys first and then then swallow them so that the "global" PreviewKeyDown does not get them?

Sure I could disable the global handler somehow when such a TextBox got focus but is this good style?

+1  A: 

You don't really have an option, aside from filtering out those keys in the global key handler.

The reason that you're having this problem is that all of the Preview* events are tunneling, meaning that controls higher in the visual tree get them first (starting at the root). The very reason why you're using this event in the first place is causing your problem.

One less than ideal option would be to register a class handler for TextBox.PreviewKeyDown (see EventManager.RegisterClassHandler()). While this would be called before your window's PreviewKeyDown handler, it will be called for all TextBoxes in your application. This may or not be what you want.

Andy
But I could derive my own TextBox and then register the handler for that class? Or maybe create a usercontrol?
codymanix
I think that would work, but I'm not sure. It's definitely worth a try.
Andy
Sorry it doesn't work. I used EventManager.RegisterClassHandler(typeof(TextBox), TextBox.PreviewKeyDownEvent, new KeyEventHandler(WatchOutHandler)) and other variations but the global handler seem to be always called first.
codymanix
I now use a flag to deactivate my global handler, it will be the simplest solution ^^
codymanix