我在c#forms应用程序中使用的标签有一个基类:
class BaseLabelGray : Label
{
public BaseLabelGray()
{
this.BackColor = Color.Transparent;
}
protected override void OnMouseEnter(EventArgs e)
{
this.ForeColor = Color.White;
this.Cursor = Cursors.Hand;
}
protected override void OnMouseLeave(EventArgs e)
{
this.ForeColor = Color.Gray;
this.Cursor = Cursors.Arrow;
}
}
当鼠标进入和离开标签时,这会改变文本和指针图标的颜色。
但是,当用户点击标签(其菜单选项)时,我会更改文字颜色并希望它保持该颜色,直到用户点击另一个标签。我的问题是,当用户鼠标离开标签时,它会再次变回。
我该如何应对?
答案 0 :(得分:3)
添加公共属性IsSelected
以跟踪选定的标签状态。在鼠标离开时设置颜色时使用该属性:
class BaseLabelGray : Label
{
private bool isSelected;
public BaseLabelGray()
{
this.BackColor = Color.Transparent;
}
public Color SelectedColor { get; set; }
public bool IsSelected
{
get { return isSelected; }
set
{
isSelected = value;
ForeColor = DefaultForeColor;
}
}
protected override void OnMouseEnter(EventArgs e)
{
this.ForeColor = Color.White;
this.Cursor = Cursors.Hand;
}
protected override void OnMouseLeave(EventArgs e)
{
this.ForeColor = DefaultForeColor;
this.Cursor = Cursors.Arrow;
}
private Color DefaultForeColor
{
get { return IsSelected ? SelectedColor : Color.Gray; }
}
}
在程序中为标签添加单击事件处理程序,您可以将单击的标签状态设置为选中,将所有其他标签设置为未选中。类似的东西:
foreach(var label in Controls.OfType<BaseLabelGray>())
label.Click += Label_Click; // subscribe
在处理程序中:
private void Label_Click(object sender, EventArgs e)
{
foreach(var label in Controls.OfType<BaseLabelGray>())
label.IsSelected = false;
var label = (BaseLabelGray)sender;
label.IsSelected = true; // select label which was clicked
}