本文介绍了为什么按钮点击事件不“冒泡可视树"?到 StackPanel 作为 MSDN 文章所述?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 MSDN 文章 了解 WPF 中的路由事件和命令中,它说

In the MSDN article Understanding Routed Events and Commands In WPF, it states

一个事件将从源元素向上冒泡(传播)可视化树,直到它被处理或到达根元素.

然而,在这个例子中,当你点击按钮时,它不会冒泡视觉树"来由父 StackPanel 事件处理,即点击按钮不会触发任何事件.

However, in this example, when you click the button, it doesn't "bubble up the visual tree" to get handled by the parent StackPanel event, i.e. clicking on the button fires no event.

为什么不呢?如果不是这个,他们所说的冒泡"是什么意思?

XAML:

<Window x:Class="TestClickEvents456.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window1" Height="300" Width="300">
    <StackPanel x:Name="TheStackPanel"
                Background="Yellow"
                MouseDown="TheStackPanel_MouseDown">
        <Button x:Name="TheButton"
                Margin="10"
                Content="Click This"/>
        <TextBlock x:Name="TheMessage"
                   Text="Click the button or the yellow area"/>
    </StackPanel>
</Window>

代码隐藏:

using System.Windows;
using System.Windows.Input;

namespace TestClickEvents456
{
    public partial class Window1 : Window
    {
        public Window1()
        {
            InitializeComponent();
        }

        private void TheStackPanel_MouseDown(object sender, MouseButtonEventArgs e)
        {
            TheMessage.Text = "StackPanel was clicked.";
        }

    }
}

推荐答案

事件冒泡,直到得到处理...

The event bubbles up, until it gets handled...

由于 Button 会通过您的鼠标点击执行某些操作,因此它会吸收您的鼠标事件并将其转换为 ClickEvent.

Since the Button does something with your mouse clicks, it absorbs your mouse event and turns it into a ClickEvent.

如果您使用 PreviewMouseDown,您会看到 StackPanel 在按钮之前首先接收事件.预览事件使用隧道向下方法.

If you use the PreviewMouseDown, you see that the StackPanel first receives the event before the button does.. Preview events use the Tunnel down approach..

这篇关于为什么按钮点击事件不“冒泡可视树"?到 StackPanel 作为 MSDN 文章所述?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 12:09