c# - 更改 RichTextBox 中选定文本的样式

标签 c# .net wpf richtextbox

如何更改 RichTextBox 中选定文本的样式(例如 Font、FontSize、Brush)?

更新: 假设我有一个 RichTextBox 和一个工具栏。用户来到 RichTextBox 框中选择文本并从工具栏更改字体大小。我想更改所选文本的样式。

最佳答案

WPF

if (this.TextEditor.Selection.IsEmpty)
    this.TextEditor.CurrentFontFamily = SelectedFont;
else
    this.TextEditor.Selection.ApplyPropertyValue(TextElement.FontFamilyProperty, SelectedFont);

或另一个 WPF 示例

 private void ChangeTextProperty(DependencyProperty dp, string value)
    {
        if (mainRTB == null) return;

        TextSelection ts = richTextBox.Selection;
        if (ts!=null)
            ts.ApplyPropertyValue(dp, value);
        richTextBox.Focus();
    }

这里有一些例子 window 更改字体和字体颜色(不是 wpf)

richTextBox1.SelectionFont = new Font("Tahoma", 12, FontStyle.Bold);
richTextBox1.SelectionColor = System.Drawing.Color.Red;

下面的另一个例子(不是wpf)

private void WriteTextToRichTextBox()
{
   // Clear all text from the RichTextBox;
   richTextBox1.Clear();
   // Set the font for the opening text to a larger Arial font;
   richTextBox1.SelectionFont = new Font("Arial", 16);
   // Assign the introduction text to the RichTextBox control.
   richTextBox1.SelectedText = "The following is a list of bulleted items:" + "\n";
   // Set the Font for the first item to a smaller size Arial font.
   richTextBox1.SelectionFont = new Font("Arial", 12);
   // Specify that the following items are to be added to a bulleted list.
   richTextBox1.SelectionBullet = true;
   // Set the color of the item text.
   richTextBox1.SelectionColor = Color.Red;
   // Assign the text to the bulleted item.
   richTextBox1.SelectedText = "Apples" + "\n";
   // Apply same font since font settings do not carry to next line.
   richTextBox1.SelectionFont = new Font("Arial", 12);
   richTextBox1.SelectionColor = Color.Orange;
   richTextBox1.SelectedText = "Oranges" + "\n";
   richTextBox1.SelectionFont = new Font("Arial", 12);
   richTextBox1.SelectionColor = Color.Purple;
   richTextBox1.SelectedText = "Grapes" + "\n";
   // End the bulleted list.
   richTextBox1.SelectionBullet = false;
   // Specify the font size and string for text displayed below bulleted list.
   richTextBox1.SelectionFont = new Font("Arial", 16);
   richTextBox1.SelectedText = "Bulleted Text Complete!";
}

关于c# - 更改 RichTextBox 中选定文本的样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11874800/

相关文章:

c# - 尝试从 Visual Studio 2013 update 4 发布 azure webjob

c# - TreeView 和 Entity Framework 绑定(bind)

WPF Listview 3 个差异列表的不同替代行颜色..?

c# - 如何在 Visual Studio 2010 中设置 winforms 项目的起始窗体

c# - BoDi.ObjectContainerException 接口(interface)无法解析 : OpenQA. Selenium.IWebDriver

c# - 如何在 ASP.NET 中使用标记声明对象

c# - 使来自第三方库的扩展方法过时

.net - .NET应用程序是否不受经典指针错误的影响?

c# - 使用 WCF 异步有好处吗?

c# - 将 WPF 按钮设置为在 IConnectionPoint 事件处理程序中可见