在 RichTextBox 中设置/取消设置斜体 [英] Set/Unset Italic in RichTextBox
问题描述
我的 C# WinForms 应用中有一个 RTF 框.
I have a RTF box in my C# WinForms app.
设置基本样式相当简单,但是当我尝试取消设置斜体样式时,我会丢失所有其他应用到选择字体的样式.
Setting basic styles is fairly simple but when I try to unset the Italic style I lose all other applied styles to the selection font.
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);
}
有没有办法在不丢失粗体、下划线等的情况下取消选择斜体属性.
Is there a way to just de-select the italic property without losing the Bold,underline ect.
推荐答案
使用 XOR 而不是 OR 来删除单个 FontStyle
- 例如:
Use an XOR rather than an OR to remove a single FontStyle
- for example:
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);
}
使用此实现,如果已将粗体或斜体样式应用于选择,则删除粗体或斜体样式不会影响其他样式.
With this implementation, removing the bold or italic style will not affect the other style if it is already applied to the selection.
奖励:
有关在更改样式后重新选择选择等其他注意事项,旧的 DevX 每日提示 你可能也会感兴趣.
For additional considerations like reselecting the selection after changing its style, an old DevX tip of the day might interest you too.
此外,我提供的特定于样式的处理程序中的通用逻辑要求被分解为特定于样式的处理程序可以利用的辅助方法 - 例如private ChangeStyle(FontStyle style)
.
Also, the common logic in the style-specific handlers I offered begs to be factored out into a helper method that the style-specific handlers can leverage - e.g. private ChangeStyle(FontStyle style)
.
这篇关于在 RichTextBox 中设置/取消设置斜体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!