Search code examples
wpfwindowseventsxamlevent-bubbling

Prevent taps from passing through buttons in XAML/WPF


In my project, I have a large container with a handler for taps. Inside this container, I also have a button. My goal is to handle all taps on the background container UNLESS the user clicks on the button. Unfortunately, when I click on the button, it fires both the click handler on the button AND the tap handler for the container.

Here's some example XAML:

<Grid Width="250" Height="250" Fill="Red" Tapped="Container_Tapped">
    <Button Click="Button_Clicked">
        <Rectangle Width="20" Height="20" Fill="Blue" />
    </Button>
</Grid>

Is there a way to handle the tap event on the button to prevent it from bubbling to the container? Any other ideas?


Solution

  • In your Container_Tapped event handler you could check the RoutedEventArgs.OriginalSource Property. If e.OriginalSource is a descendant of your button do nothing.

    For that Visual.IsDescendantOf Method could be helpful.