【发布时间】:2020-11-01 08:14:31
【问题描述】:
我有 WPF UI 元素,当鼠标光标进入此元素时应隐藏,当鼠标光标离开此元素时可见。为此,我使用事件OnMouseEnter 和OnMouseLeave,如下所示:
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;
}
<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,但我不明白那里附上的解决方案。
我需要做些什么来防止这些事件循环?
【问题讨论】: