在RichTextBox中设置/取消设置斜体

时间:2014-02-24 01:14:00

标签: c# winforms richtextbox

我的C#WinForms应用程序中有一个RTF框。

设置基本样式非常简单但是当我尝试取消设置Italic样式时,我将所有其他应用样式丢失到选择字体。

if (rtf.SelectionFont.Style.HasFlag(FontStyle.Italic))
{
     rtf.SelectionFont = new Font(rtf.SelectionFont.FontFamily, rtf.SelectionFont.Size, rtf.SelectionFont.Style | FontStyle.Regular);
}
else
{
     rtf.SelectionFont = new Font(rtf.SelectionFont.FontFamily, rtf.SelectionFont.Size, rtf.SelectionFont.Style | FontStyle.Italic);
}

有没有办法在不丢失粗体的情况下取消选择斜体属性,下划线等。

2 个答案:

答案 0 :(得分:2)

您应该尝试迭代枚举并将样式重新组合在一起。如下所示:

FontStyle oldStyle = rtf.SelectionFont.Style;
FontStyle newStyle = FontStyle.Regular;
foreach (Enum value in Enum.GetValues(oldStyle.GetType()))
{
    if (oldStyle.HasFlag(value) && !value.Equals(FontStyle.Italic))
    {
        newStyle = newStyle | (FontStyle)value;
    }
}

rtf.SelectionFont = new Font(rtf.SelectionFont.FontFamily, rtf.SelectionFont.Size, newStyle);

答案 1 :(得分:1)

使用XOR而不是OR来删除单个FontStyle - 例如:

private void btnBold_Click(object sender, EventArgs e)
{
    var currentStyle = rtf.SelectionFont.Style;
    var newStyle =
        rtf.SelectionFont.Bold ?
        currentStyle ^ FontStyle.Bold :
        currentStyle | FontStyle.Bold;

    rtf.SelectionFont =
        new Font(
            rtf.SelectionFont.FontFamily,
            rtf.SelectionFont.Size,
            newStyle);
}

private void btnItalic_Click(object sender, EventArgs e)
{
    var currentStyle = rtf.SelectionFont.Style;
    var newStyle =
        rtf.SelectionFont.Italic ?
        currentStyle ^ FontStyle.Italic :
        currentStyle | FontStyle.Italic;

    rtf.SelectionFont =
        new Font(
            rtf.SelectionFont.FontFamily,
            rtf.SelectionFont.Size,
            newStyle);
}

使用此实现,如果已将其应用于选择,则删除粗体或斜体样式不会影响其他样式。

<强>奖金:

对于其他注意事项,例如在更改其样式后重新选择选择,旧的DevX tip of the day也可能会让您感兴趣。

此外,我提供的特定于样式的处理程序中的常见逻辑需要考虑到特定于样式的处理程序可以利用的辅助方法 - 例如, private ChangeStyle(FontStyle style)