Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Routing Key events to other control

Is there any standard way to route all Key events from the control A to other control B? I wish that the keyboard focus will still be on A however the event handler of A would trigger the all event handlers of B for the key events.

edit: Clarification: calling a specific event handler I wrote for B is not enough. I need to mimic the actual event. So for example I want that if a key is sent to a TextBox, it would be written to the TextBox. The solution given below does not do that (not to mention the fact that if new event handlers are added to B it completely fails).

I'm aware that WPF differentiates between logical focus and keyboard focus, but I need both focuses to remain on control A, but in a certain cases route its incoming event to other controls.

like image 316
Elazar Leibovich Avatar asked Sep 14 '09 12:09

Elazar Leibovich


People also ask

What are routed events?

From a functional perspective, a routed event is a type of event that can invoke handlers on multiple listeners in an element tree, not just on the event source. An event listener is the element where an event handler is attached and invoked. An event source is the element or object that originally raised an event.

What is bubbling and tunneling in WPF?

The difference between a bubbling and a tunneling event is that a tunneling event will always start with a preview. In a WPF application, events are often implemented as a tunneling/bubbling pair. So, you'll have a preview MouseDown and then a MouseDown event.


1 Answers

Couldn't you do something like this?

  private void button1_Click(object sender, RoutedEventArgs e)
  {
     // Check if the event needs to be passed to button2's handler
     if (conditionIsMet)
     {
        // Send the event to button2
        button2.RaiseEvent(e);
     }
     else
     {
        // button1's "Click" code
     }
  }

  private void button2_Click(object sender, RoutedEventArgs e)
  {
     // button2's "Click" code
  }

Edit: Modified code to use the RaiseEvent() method to programmatically raise a specific event, rather than just calling the event handler for button2.

like image 51
Donut Avatar answered Sep 25 '22 01:09

Donut