문제

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

도움이 되었습니까?

해결책

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.

다른 팁

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.

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top