同时正确更改字体样式

Properly change Font Style simultaneously

选中多个复选框时,如何在不使用大量 if / else if 条件的情况下正确更改文本的字体样式?

PS。我知道在一个文本中使用多种样式时该使用什么,但我不想用很长的 if/else 条件来实现它。

这是我拥有的:

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();
    }
  • 将相关的 FontStyle 分配给每个 CheckBox.Tag 属性(在 Form 构造函数或 Load 事件中)。

  • 为所有 CheckBoxes CheckedChange 事件分配一个事件处理程序(它是在设计器中设置的,在这里;当然你也可以在构造函数中添加它).

  • FontStyle是一个标志。您可以使用 | 添加它,使用 &~ 删除它。

如果需要,您可以添加条件以相互排除下划线和删除线样式。


 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);
 }


正如 Jimi 已经提到的,但在这里您也可以使用 LINQ 实现您的目标。

private void UpdateTextBoxFontStyle()
{
   var fs = System.Drawing.FontStyle.Regular;

   var checkedStyles = Controls.OfType<CheckBox>()
          .Where(x => x.Checked)
          .Where(x => x.Tag is System.Drawing.FontStyle)
          .Select(x => (System.Drawing.FontStyle) x.Tag).ToList();

   foreach (var style in checkedStyles) fs |= style;
   lblTestFont.Font = new System.Drawing.Font("Segoe UI", 9f, fs, System.Drawing.GraphicsUnit.Point);
}

并为每个复选框分配 CheckedChanged 事件处理程序。

foreach (Control control in Controls)
      if (control is CheckBox checkBox)
         checkBox.CheckedChanged += (s, e) => UpdateTextBoxFontStyle();