当鼠标进入它所在区域时,更改控件背景
本文关键字:背景 控件 区域 鼠标 | 更新日期: 2023-09-27 17:52:13
我有一个带有上下文菜单的标签控件,我想在鼠标进入它的矩形时改变它的背景色,并在鼠标离开时返回它的父背景色。
改变背景是在MouseEnter和MouseLeave事件处理程序中实现的。
问题是,当我点击右键和上下文菜单显示MouseLeave事件被提出和控制的背景被改变回它的父背景,但我希望它保持不变。
代码如下:
//Label controls are created dynamically and added to a StackPanel
ContextMenu contextMenu = new ContextMenu();
contextMenu.Items.Add("MenuItem");
Label deviceLabel = new Label()
{
Content = "LabelText",
ContextMenu = contextMenu
};
//when mouse enters label bounds change it's background to AliceBlue color
deviceLabel.MouseEnter += delegate
{
deviceLabel.Background = new SolidColorBrush(Colors.AliceBlue);
};
//when mouse leaves label bounds get it's parent panel control background color back
deviceLabel.MouseLeave += delegate
{
deviceLabel.Background = (Brush)this.Parent.GetValue(Panel.BackgroundProperty);
};
stackPanel.Children.Add(deviceLabel);
那么我怎么能离开标签背景与AliceBlue的颜色,而它的上下文菜单是打开的?
您需要检查是否有IsOpen在MouseLeave事件中,如果是,不要改变背景,而是附加到一个新的事件到ContextMenu。关闭,并更改背景颜色deviceLabel