UWP:不会在子元素上触发PointerPressed

时间:2019-02-26 08:36:14

标签: c# uwp event-handling mouseevent event-bubbling

我有一个UWP应用,其中RelativePanel“父”包含另一个RelativePanel“子”。 他们两个都应该能够以不同的方式处理PointerPressed事件。

当我单击父级时,正确触发了父级的PointerPressed事件处理程序,但是当我单击子级时,再次仅触发了父级的PointerPressed事件处理程序,因此,子级的PointerPressed事件处理程序永远不会被调用。

如何配置子项,以便调用其PointerPressed事件处理程序?

以下是创建这些元素的代码摘录(所有操作均在后面的代码中完成,因为这些元素应在运行时创建):

public class ChildView
{
    public RelativePanel View { get; set; }

    public ChildView()
    {
        View.Width = 18;
        View.Height = 18;
        View.SetValue(Canvas.ZIndexProperty, 30);  // we want the child always on top of the parent
        View.Background = new SolidColorBrush(Colors.Transparent);

        // Add the gesture recognizers:
        View.Holding += HandleLongPressGesture;
        View.PointerPressed += HandleTapGesture;
        View.PointerReleased += HandlePointerReleased;
        View.DoubleTapped += HandleDoubleTapGesture;
    }

    public void HandleLongPressGesture(object sender, HoldingRoutedEventArgs e)
    {
        // my logic
    }
    private void HandlePointerReleased(object sender, PointerRoutedEventArgs e)
    {
        // my logic
    }
    private void HandleDoubleTapGesture(object sender, DoubleTappedRoutedEventArgs e)
    {
        // my logic
    }
    private void HandleTapGesture(object sender, PointerRoutedEventArgs e)
    {
        // my logic
    }
}

public class ParentView
{
    private ChildView child;

    public RelativePanel View { get; set; }

    public ParentView()
    {
        child = new ChildView();
        View.Children.Add(child.View);
        View.PointerPressed += HandleTapGesture;
        View.PointerReleased += HandlePointerReleased;
    }

    private void HandlePointerReleased(object sender, PointerRoutedEventArgs e)
    {
        // my logic
    }
    private void HandleDoubleTapGesture(object sender, DoubleTappedRoutedEventArgs e)
    {
        // my logic
    }
}

2 个答案:

答案 0 :(得分:0)

将子面板的背景设置为透明。

事件触发时,请确保您执行.Handled = true;  传入的处理程序args上,以防止传播到父控件。

答案 1 :(得分:0)

我知道这并不完全是您的问题的答案,但是也许它将以某种方式帮助您进行调试。

好的,所以我建立了一个简单的项目(在将代码添加到问题之前),并且无法复制问题。

基本上,孩子点击事件被正确触发,然后父点击事件随后被立即触发,在这种情况下,对我来说这是正确的。

XAML

<Grid>
    <RelativePanel Name="Parent" HorizontalAlignment="Left" Height="460" Margin="437,162,0,0" VerticalAlignment="Top" Width="458" Background="#FFFF5C5C" PointerPressed="Parent_PointerPressed">
        <RelativePanel Name="Child" HorizontalAlignment="Left" Height="360" Margin="62,50,0,0" VerticalAlignment="Top" Width="334" Background="#FF3B9C9C" PointerPressed="Child_PointerPressed"/>
    </RelativePanel>
</Grid>

C#

    private void Parent_PointerPressed(object sender, PointerRoutedEventArgs e)
    {
        // Breaks here when Parent is pressed
        // Also breaks here after breaking on Child_PointerPressed
    }

    private void Child_PointerPressed(object sender, PointerRoutedEventArgs e)
    {
        // Breaks here when Child is pressed
    }