Pregunta

I feel like a real noob posting this, but I can't seem to find anything for this...

I have a control that I'm basically trying to toggle the fontstyle between bold and not bold. This should be simple...

However, you can't acccess the Control.Font.Bold property as it is read only, therefore, you need to change the Font property.

To make it bold, I just do this:

this.btn_buttonBolding.Font = new Font(this.btn_buttonBolding.Font, FontStyle.Bold);

Not ideal, but it works. However, how do I go about removing this bold style (once it is bold already)?

I looked hard for duplicates; closest I could find was this, but it doesn't quite answer my situation: Substract Flag From FontStyle (Toggling FontStyles) [C#]

And this which gives how to set it, but not remove it: Change a font programmatically

Am I missing a simple constructor for the font that could do this? Or am I just missing something easier?

¿Fue útil?

Solución

The FontStyle enum contains 5 distinct values. The one that reset your previous set is FontStyle.Regular

Regular Normal text.
Bold Bold text.
Italic Italic text.
Underline Underlined text.
Strikeout Text with a line through the middle.

It's a bitwise enum where Regular is 0. So setting this value alone reset all other flags

Otros consejos

I know this is a bit old, but I was faced with the exact same problem and came up with this:

Font opFont = this.btn_buttonBolding.Font;
if(value)
{
    this.btn_buttonBolding.Font = new Font(opFont, opFont.Style | FontStyle.Bold);
}
else 
{
    this.btn_buttonBolding.Font = new Font(opFont, opFont.Style & ~FontStyle.Bold);
}

The magic is in the "~" which is the bitwise NOT. (See the MSDN KB article "~Operator")

Try this:

    private void btn_buttonBolding_Click(object sender, EventArgs e)
    {
        var style = btn_buttonBolding.Font.Bold ? FontStyle.Regular : FontStyle.Bold;
        btn_buttonBolding.Font = new Font(this.Font, style);
    }
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top