So I’m working on a basic subclass of Label that supports editing. The editing part works fine–I insert a text box with no background color or border on click, commit changes on enter or loss of focus.
The little thing that’s giving me trouble is related to some basic font styling. The label is to underline with the MouseHover event (like a hyperlink) and then lose the underline afterwards. Most of the time, it works, but occasionally, the MouseHover will cause the font to revert to the Winforms default–8pt sans-serif–instead of performing the operation.
Here’s the event handler:
void BWEditableLabel_MouseHover(object sender, EventArgs e)
{
_fontBeforeHover = Font;
Font hoverFont = new Font(
_fontBeforeHover.FontFamily.Name,
_fontBeforeHover.Size,
_fontBeforeHover.Style | FontStyle.Underline
);
Font = hoverFont;
}
Some of you may observe that the last line doesn’t simply say:
Font = new Font(Font, Font.Style | FontStyle.Underline)
I tried that, and the problem came about. The current version before you was an attempt that I made to resolve the issue.
I think I solved it, though it feels like a bit of a patch instead of the cleanest solution. I did away with
_fontBeforeHoverand created_originalFont. I then overrode theFontproperty of the label and in the setter, set_originalFontto whatever the label is being set to. Then, in myMouseHoverandMouseLeaveevents, I used a new method,SetFont()to change the font. WithinSetFont(), I assignbase.Fontinstead of using the overridden property. If I used the overridden property, I’d always be reassigning_originalFontto whatever I change the label’s font to during the events.Sure would be nice if I didn’t need all that extra code, though 🙂
I’m definitely open to more suggestions.