views:

120

answers:

3

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.

A: 

What if you use the MouseEnter and MouseLeave events? MouseEnter sets it to underlined and MouseLeave reverts it.

hjb417
Just curious--is this suggestion just a "try and see" or does MouseEnter generally behave a bit differently in relation to these sorts of things?
Brian Warshaw
hjb417
A: 

I think I solved it, though it feels like a bit of a patch instead of the cleanest solution. I did away with _fontBeforeHover and created _originalFont. I then overrode the Font property of the label and in the setter, set _originalFont to whatever the label is being set to. Then, in my MouseHover and MouseLeave events, I used a new method, SetFont() to change the font. Within SetFont(), I assign base.Font instead of using the overridden property. If I used the overridden property, I'd always be reassigning _originalFont to 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.

Brian Warshaw
A: 

Sorry for the double answer, but maybe you might want to consider drawing the text yourself via DrawString in the paint event, that way you're not setting the Font property. The Font property gets it's value from the Parent's font unless explicitly set.

hjb417