从字体样式中减去标志(切换字体样式)[C#]

Substract Flag From FontStyle (Toggling FontStyles) [C#](从字体样式中减去标志(切换字体样式)[C#])
本文介绍了从字体样式中减去标志(切换字体样式)[C#]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个小问题.我有一个 1 RichTextBox 和 2 个按钮.

I have a little problem. I have one 1 RichTextBox and 2 Buttons.

我有切换粗体 FStyle"和切换斜体 FStyle"的 2 个按钮.

I have that 2 buttons for "toggle Bold FStyle" and "toggle Italic FStyle".

我想切换字体样式而不影响其他字体样式.希望你能理解我.

I want to toggle FontStyles without affecting other FontStyles. I hope you understand me.

以下代码在组合 FontStyles 时有效,但在分离/减去FontStyles 时无效.

Below code works when combining FontStyles but is not working when seperating/substracting FontStyles.

private void button1_Click(object sender, EventArgs e)
{
    richTextBox1.SelectionFont = new Font(richTextBox1.Font, (richTextBox1.SelectionFont.Bold == false ? richTextBox1.SelectionFont.Style | FontStyle.Bold : richTextBox1.SelectionFont.Style));
}

private void button2_Click(object sender, EventArgs e)
{
    richTextBox1.SelectionFont = new Font(richTextBox1.Font, (richTextBox1.SelectionFont.Italic == false ? richTextBox1.SelectionFont.Style | FontStyle.Italic : richTextBox1.SelectionFont.Style));
}

  1. 我将所选文本加粗
  2. 我将所选文本设为斜体
  3. 我想在粗体仍处于活动状态(或相反)时删除斜体

推荐答案

最简单的方法是使用按位异或(^),它只是切换值:

The easiest way is to use bitwise XOR (^), which just toggles the value:

private void button1_Click(object sender, EventArgs e)
{
    richTextBox1.SelectionFont = new Font(richTextBox1.Font,
        richTextBox1.SelectionFont.Style ^ FontStyle.Bold);
}

private void button2_Click(object sender, EventArgs e)
{
    richTextBox1.SelectionFont = new Font(richTextBox1.Font,
        richTextBox1.SelectionFont.Style ^ FontStyle.Italic);
}

这篇关于从字体样式中减去标志(切换字体样式)[C#]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)