0

This is my first question so please go easy :)

I am new to WPF and Desktop based applications and I am studying Event Handling. Going through Bubbling and Tunneling I can not find an example anywhere that explains how to use tunneling on a Button_Click.

Basically when I click a button I need the parent control (in this case a grid) to handle the event first and do some checks before allowing the Button_Click to take place. The problem I am having is I can use the Grid_PreviewMouseDown to capture the event but this is ambiguous! It does not tell me (at least i think it doesnt) what control caused the handler to trigger.

What can i do to determine the PreviewMouseDown was triggered by a Button Click? Or: Is there an alternative/better was to tunnel a Button_Click?

Thanks

H.B.
  • 166,899
  • 29
  • 327
  • 400
Andy Clark
  • 3,363
  • 7
  • 27
  • 42

1 Answers1

1

In your handler, you should inspect the Source of the event to get the control which initiated it. Just note that it is not readonly and could be changed so the Source refers to a different control.

You'll probably have better luck registering with the PreviewMouseLeftButtonDown event to get left clicks and not just any click.

If your handler is meant to only look for the left mouse click, you could use this code:

private void Grid_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
    Button button = e.Source as Button;
    if (button != null)
    {
        // button is being clicked, handle it
    }
}
Jeff Mercado
  • 129,526
  • 32
  • 251
  • 272
  • @Mrs: It would depend on your situation. If your handler will be dedicated to handle button clicks, then the code in my update would be fine. Otherwise if your handler will handle other control clicks, it may be easier to check using `is`. – Jeff Mercado Aug 11 '11 at 11:36
  • The "object sender" parameter is the button that was clicked, right?, so a simple "bool isAbutton = sender is Button;" would work. – matfillion Aug 11 '11 at 14:05
  • 2
    @oXeNoN: No, not in this case. The `sender` is the control that the event is registered on. In this case, it's registered on a `Grid` and not the `Button` itself. `sender` would be referring to the `Grid`. – Jeff Mercado Aug 11 '11 at 19:19