防止水龙头通过XAML / WPF中的按钮

时间:2022-07-02 03:44:33

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:

这是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?

有没有办法处理按钮上的点击事件,以防止它冒泡到容器?还有其他想法吗?

2 个解决方案

#1


5  

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

在您的Container_Tapped事件处理程序中,您可以检查RoutedEventArgs.OriginalSource属性。如果e.OriginalSource是你的按钮的后代什么也不做。

For that Visual.IsDescendantOf Method could be helpful.

对于Visual.IsDescendantOf方法可能会有所帮助。

#2


0  

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!)

这是在Win RT中执行此操作的动态方式,无需知道按钮的确切名称(如果您有一堆按钮可用,例如数据绑定时很有用!)

    ' 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)
        Loop
    End If

#1


5  

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

在您的Container_Tapped事件处理程序中,您可以检查RoutedEventArgs.OriginalSource属性。如果e.OriginalSource是你的按钮的后代什么也不做。

For that Visual.IsDescendantOf Method could be helpful.

对于Visual.IsDescendantOf方法可能会有所帮助。

#2


0  

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!)

这是在Win RT中执行此操作的动态方式,无需知道按钮的确切名称(如果您有一堆按钮可用,例如数据绑定时很有用!)

    ' 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)
        Loop
    End If