WPF 如何将事件传递给兄弟元素

标签 wpf events event-bubbling

我已阅读帖子 Button.MouseDown 接下来,我想再问 1 个问题。 我的 XAML 如下:

    <Window.Resources>
    <Style TargetType="{x:Type ContentControl}">
        <Setter Property="BorderThickness" Value="5" />
        <Setter Property="Padding" Value="10" />
        <Setter Property="Background" Value="PaleGreen" />
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type ContentControl}">
                    <Border Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Padding="{TemplateBinding Padding}">
                        <ContentPresenter/>
                    </Border>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</Window.Resources>

<StackPanel Tag="Panel" PreviewMouseDown="PreviewMouseDown" MouseDown="MouseDown">
    <ContentControl BorderBrush="Red" Tag="C1" PreviewMouseDown="PreviewMouseDown" MouseDown="MouseDown">
        <ContentControl BorderBrush="Green" Tag="C2" PreviewMouseDown="PreviewMouseDown" MouseDown="MouseDown">
            <StackPanel Tag="Panel2" PreviewMouseDown="PreviewMouseDown" MouseDown="MouseDown">
                <ContentControl Content="Click Me" BorderBrush="Blue" Tag="C3" PreviewMouseDown="PreviewMouseDown" MouseDown="MouseDown"/>
                <ContentControl Content="Click Me2" BorderBrush="Blue" Tag="C33" PreviewMouseDown="PreviewMouseDown" MouseDown="MouseDown"/>
            </StackPanel>
        </ContentControl>
    </ContentControl>
</StackPanel>

我的cs如下:

        private void PreviewMouseDown(object sender, MouseButtonEventArgs e)
    {
        Debug.WriteLine(((FrameworkElement) sender).Tag + " Preview");
    }

    private void MouseDown(object sender, MouseButtonEventArgs e)
    {
        Debug.WriteLine(((FrameworkElement) sender).Tag + " Bubble");
    }

如何将鼠标上/下事件从 C3 传输到 C33?基本上我希望来自 1 个 sibling 的所有事件也能到达其他 sibling 。

最佳答案

您可以从 C3 的 EventHandler 调用 C33 的 RaiseEvent 方法:

private void C3_MouseDown(object sender, MouseButtonEventArgs e)
{
  C33.RaiseEvent(e);
}

顺便说一句,我注意到您正在使用 Tag 来命名您的元素。用于此的更合适的属性是 Name 属性。一般规则是 Tag 属性的使用仅适用于大约 0.001% 的 WPF 程序(十万分之一)。在所有常用的情况下,都有更好的方法来做同样的事情。

关于WPF 如何将事件传递给兄弟元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3090769/

相关文章:

wpf - ScrollViewer 中的用户控件不会在 WPF 中滚动

java - java程序退出时调用函数

javascript - 停止事件冒泡 - onclick 监听器

javascript - 事件捕获、事件冒泡和 jQuery.on()

c# - 防止数据网格中的行更改

wpf - 当条件不等于时触发

c# - wpf自定义控件: audiowaveform rectangle with selection slider

javascript - Promise.all() - 在触发多个事件监听器后执行某些操作

javascript - 内部 div 的事件累积外部 div 的事件数

javascript - 如何只点击模态外观而不点击对话框/内容?