Home » Windows » Prevent taps from passing through buttons in XAML/WPF

Prevent taps from passing through buttons in XAML/WPF

Posted by: admin February 27, 2018 Leave a comment


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" />

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


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.


Here’s a dynamic way to do it in Win RT, without needing to know the exact name of the button (useful if you have a pile of buttons to work with, such as when databinding!)

    ' Verify that the sender is not a button (or one of its children)
    If Not e.OriginalSource.Equals(sender) Then
        Dim parentObj = VisualTreeHelper.GetParent(e.OriginalSource)
        Do While Not parentObj.Equals(sender)
            If TypeOf parentObj Is Button Then Return
            parentObj = VisualTreeHelper.GetParent(parentObj)
    End If