Reputation: 4777
I have a base class for the labels I'm using in a c# forms application:
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;
}
}
This changes the color of the text and pointer icon when the mouse enters and leaves the label.
However, when the user clicks the label (Its a menu selection) i change the text color and want it to stay that color untill the user clicks another label. My problem is that when the users mouse leaves the label it gets changed back again.
How can I cope with this??
Upvotes: 1
Views: 3008
Reputation: 236318
Add public property IsSelected
to track selected state of label. Use that property when you are setting color on mouse leave:
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; }
}
}
In your program add click event handler for labels, where you will set clicked label state to selected, and all other labels to non-selected. Something like:
foreach(var label in Controls.OfType<BaseLabelGray>())
label.Click += Label_Click; // subscribe
And in handler:
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
}
Upvotes: 3