我有一个带有上下文菜单的Label控件,我想在鼠标进入矩形时更改它的背景颜色,并在鼠标离开时返回它的父背景颜色。
在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颜色?
答案 0 :(得分:2)
您需要检查MouseLeave事件中的contextMenu.IsOpen是否不更改背景,而是将新事件附加到ContextMenu.Closed,并在引发时更改背景颜色deviceLabel