【问题标题】:How to handle a click event and then pass through to the underlying application in WPF如何处理点击事件然后传递给WPF中的底层应用程序
【发布时间】:2021-10-29 05:15:57
【问题描述】:

我有一个背景为 {x:Null} 且 AllowTransparency=True 的 WPF 窗口

<Window x:Class="ClickThrough"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="SeeThru" Height="200" Width="200"
        Topmost="True"
        WindowStyle="None" 
        AllowsTransparency="True"
        Background="{x:Null}">

    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="30" />
            <RowDefinition Height="80"/>
            <RowDefinition Height="20"/>
        </Grid.RowDefinitions>
        <Border Background="CadetBlue" HorizontalAlignment="Stretch" VerticalAlignment="Stretch"
                CornerRadius="5,5,0,0" Margin="-1,0,-1,0" MouseLeftButtonDown="DragWindow">
        </Border>
        <Grid MouseLeftButtonUp="UIElement_OnMouseLeftButtonUp" Grid.Row="1"></Grid>
    </Grid>
</Window>

我可以点击“窗口”,点击穿过窗口,底层应用程序接收到它。太棒了。不过我也希望能够处理点击事件,然后允许它传递到底层应用程序。

内部 Grid 上的事件处理程序不注册事件。

private void UIElement_OnMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
    Console.WriteLine("clicked");
    e.Handled = false;
}

如果我将内部网格中的背景更改为一种颜色。

<Grid MouseLeftButtonUp="UIElement_OnMouseLeftButtonUp" Grid.Row="1" Background="Aqua">

现在接收到事件,但是即使将handled 设置为false,点击也不会冒泡到底层应用程序。

这可能吗?

【问题讨论】:

    标签: wpf click transparency event-passthrough


    【解决方案1】:

    在您的点击事件处理程序方法中,在您通过执行所需代码“处理”它之后,只需设置:

    e.Handled = false;
    

    这告诉隧道/冒泡事件它认为您尚未处理此点击,并将允许执行其他点击事件。

    【讨论】:

    • 这似乎不适用于窗口,因为它首先没有接收到事件。该事件仅在有非透明/非空背景时注册。
    • 我已更新问题以澄清这一点
    • @Druzil 在您更新的问题中,我相信点击没有冒泡的原因是因为您使用的是Message.Show,它改变了视觉/逻辑树的焦点。将其替换为Console.WriteLine("Click"),它应该完全通过UIElement_OnMouseLeftButtonUp 方法(因为您以e.Handled = false 结束了该方法),然后它会允许触发其他点击事件。
    • 感谢@Tam Bui,不幸的是我试过了,但仍然无法正常工作。
    • 您是否尝试过切换到“预览”点击事件?当 UIElement_MouseLeftButtonUp 执行时,您要执行的“基础应用程序”是什么?也许我不明白你想要什么,如果你提供一个最小的可重现样本来隔离你的问题会更好,因为代码 sn-ps 可能会隐藏你的问题的根源。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-11
    • 2020-12-12
    • 1970-01-01
    • 1970-01-01
    • 2016-06-07
    • 2011-05-02
    相关资源
    最近更新 更多