views:

35

answers:

3

Hi there,

I have implemented a UserControl. Then I would like to handle an event that is originally handled by Window (keyboard press). What is the best way to route the event caught by another component (higher in the components' tree)?

Thanks in advance for the replies and hints!

Cheers

A: 

I believe you cannot gurantee that. Window class is wrapping Win32 message-based event model and this will be the only WPF entity which will have access to those information.

I suggest that you create an attached property (which will be used by the Window) and implement the routing of the events yourself so that controls could subscribe to.

Aliostad
A: 

You can attach the routed handler specifying that you want to handle handled messages as well:

this.AddHandler(routedEvent, handler, true);

where this is an UIElement or derived class.

However there may still be events (key presses in this case) which don't make it past the window, not sure.

Alex Paven
this will not work if some control above stops the bubbling. hence "no guarantee"
Aliostad
Actually, how exactly can the control stop the bubbling? Setting Handled=true does not stop it, only marks it as handled.
Alex Paven
+1  A: 

It depends on the event you're trying to access. If it's a Preview event and the Window is setting e.Handled to true you'll need to use the method Alex suggests to circumvent the Window's handling of the tunneling. If it is a bubbling event (i.e. KeyDown) you don't need to do anything special since bubbling events hit the handlers on child elements first and go up the visual tree so the Window handler won't occur until after your UC's.

One thing you need to be careful with using Key events is that the event is only going to get picked up by your UC in the first place if the Focus is on or inside of it. This isn't something you need to worry about with things like Mouse events since they start at a specific location in the tree.

John Bowen