Search code examples
c#winformscheckboxfont-style

Properly change Font Style simultaneously


enter image description here

How do I properly change the Font Style of the text without using a lot of if / else if conditions when checking multiple checkboxes?

PS. I know what to use when having multiple styles in one text but I d not want a long if/else conditions to achieve it.

Here's what I Have:

public void updateFont()
    {
        //Individual
        if (checkBox_Bold.Checked)
            fontStyle = fontFamily.Style | FontStyle.Bold;
        if (checkBox_Italic.Checked)
            fontStyle = fontFamily.Style | FontStyle.Italic;
        if (checkBox_Underlined.Checked)
            fontStyle = fontFamily.Style | FontStyle.Underline;
        if (checkBox_StrikeOut.Checked)
            fontStyle = fontFamily.Style | FontStyle.Strikeout;
        if (!checkBox_Bold.Checked && !checkBox_Italic.Checked && !checkBox_Underlined.Checked && !checkBox_StrikeOut.Checked)
            fontStyle = FontStyle.Regular;


        fontFamily = new Font(cbox_FontFamily.SelectedItem.ToString(), Convert.ToInt32(fontSize), fontStyle);
        pictureBox_Canvass.Invalidate();
    }

Solution

    • Assign the related FontStyle to each CheckBox.Tag property (in the Form constructor, or Load event).

    • Assign a single Event handler to all CheckBoxes CheckedChange event (it's set in the designer, here; but it of course you can add it in the constructor as well).

    • FontStyle is a flag. You can use | to add it and &~ to remove it.

    You could add a condition to mutually excludes the Underline and Strikeout styles, if required.


     FontStyle fontStyle = FontStyle.Regular;
    
     public form1()
     {
        InitializeComponent();
    
        this.chkBold.Tag = FontStyle.Bold;
        this.chkItalic.Tag = FontStyle.Italic;
        this.chkUnderline.Tag = FontStyle.Underline;
        this.chkStrikeout.Tag = FontStyle.Strikeout;
     }
    
     private void chkFontStyle_CheckedChanged(object sender, EventArgs e)
     {
        CheckBox checkBox = sender as CheckBox;
        FontStyle CurrentFontStyle = (FontStyle)checkBox.Tag;
        fontStyle = checkBox.Checked ? fontStyle | CurrentFontStyle : fontStyle &~CurrentFontStyle;
        lblTestFont.Font = new Font("Segoe UI", 10, fontStyle, GraphicsUnit.Point);
     }
    


    Set Font Style