Question

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

Was it helpful?

Solution

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
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top