我的 C# WinForms 应用程序中有一个 RTF 框。
设置基本样式相当简单,但是当我尝试取消设置斜体样式时,我会丢失所有其他应用到选择字体的样式。
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);
}
有没有办法在不丢失粗体、下划线等的情况下取消选择斜体属性。
请您参考如下方法:
使用 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 样式).
