C# WPF OnMouseEnter 和 OnMouseLeave 循环

标签 c# wpf

我有 WPF UI 元素,当鼠标光标进入此元素时应隐藏这些元素,当鼠标光标离开此元素时应显示这些元素。为此,我使用事件 OnMouseEnterOnMouseLeave,如下所示:

private void TextBlock_MouseEnter(object sender, MouseEventArgs e)
{
    (e.Source as UIElement).Visibility = Visibility.Hidden;
}

private void TextBlock_MouseLeave(object sender, MouseEventArgs e)
{
    (e.Source as UIElement).Visibility = Visibility.Visible;
}

(以下代码来自 https://learn.microsoft.com/en-us/dotnet/api/system.windows.controls.panel.zindex?view=netframework-4.8 )

<Canvas>
            <Rectangle Canvas.ZIndex="1" Width="100" Height="100" Canvas.Top="100" Canvas.Left="100" Fill="blue" MouseEnter="TextBlock_MouseEnter" MouseLeave="TextBlock_MouseLeave"/>
            <Rectangle Canvas.ZIndex="2" Width="100" Height="100" Canvas.Top="150" Canvas.Left="150" Fill="yellow" MouseEnter="TextBlock_MouseEnter" MouseLeave="TextBlock_MouseLeave"/>
            <Rectangle Canvas.ZIndex="3" Width="100" Height="100" Canvas.Top="200" Canvas.Left="200" Fill="green" MouseEnter="TextBlock_MouseEnter" MouseLeave="TextBlock_MouseLeave"/>

            <!-- Reverse the order to illustrate z-index property -->

            <Rectangle Canvas.ZIndex="3" Width="100" Height="100" Canvas.Top="300" Canvas.Left="200" Fill="green" MouseEnter="TextBlock_MouseEnter" MouseLeave="TextBlock_MouseLeave"/>
            <Rectangle Canvas.ZIndex="2" Width="100" Height="100" Canvas.Top="350" Canvas.Left="150" Fill="yellow" MouseEnter="TextBlock_MouseEnter" MouseLeave="TextBlock_MouseLeave"/>
            <Rectangle Canvas.ZIndex="1" Width="100" Height="100" Canvas.Top="400" Canvas.Left="100" Fill="blue" MouseEnter="TextBlock_MouseEnter" MouseLeave="TextBlock_MouseLeave"/>
        </Canvas>

但是当我运行程序并将光标悬停在元素上时,it starts to flicker and eat up quite a lot of CPU resources .

调试显示当我将光标悬停在元素上时,events loops直到我将光标从元素上移开。

我看到了this article ,但我不明白那里附带的解决方案。

我需要做什么来防止这些事件循环发生?

最佳答案

当您将 UIElement 的 Visibility 更改为 Hidden 时,您实际上是在触发 MouseLeave 事件,因为鼠标 HitTest 现在是在它后面的元素上执行的。然后运行您的事件处理程序,它将 Visibility 设置为 Visible,然后触发 MouseEnter 事件。因此会出现闪烁。

解决这个问题的一个想法是使用不透明度而不是可见性。尝试:

private void TextBlock_MouseEnter(object sender, MouseEventArgs e)
{
  (e.Source as UIElement).Opacity = 0;
}

private void TextBlock_MouseLeave(object sender, MouseEventArgs e)
{
  (e.Source as UIElement).Opacity = 1;
}

关于C# WPF OnMouseEnter 和 OnMouseLeave 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64629873/

相关文章:

c# - VS2022 VueJs 独立模板 TS 错误

c# - Xamarin.Forms DatePicker 时间

WPF - 虚拟化 WrapPanel

wpf - 如何在此代码段中获取 TextBlock Text 属性?

c# - 在 WPF 中打开新窗口引发异常

C# 如何只追加文本文件的末尾和特定位置?

c# - 从图形调整图像大小?

c# - 具有 LINQ、JOIN 和 ORDER BY 的 Entity Framework 以及连接表中的列

wpf - 获取 WPF 弹出窗口的 AutomationElement

c# - 如何在 WPF 中强制显示工具提示