2011-04-21 29 views
0

我有一个带上下文菜单的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); 

所以,我怎么能离开标签背景色艾莉斯蓝,而它的上下文菜单是开放的?

回答

2

您将需要检查MouseLeave事件中的contextMenu.IsOpen是否不会更改背景,而是将新事件附加到ContextMenu.Closed,并在此时更改背景颜色deviceLabel上调。

+0

Thanks!it works – ArtemKizil 2011-04-21 11:50:56

相关问题