在RichTextBox中更改所选文本的样式

4
我该如何更改在RichTextBox中选中文本的样式(例如字体、字号、刷子)?
更新:假设我有一个RichTextBox和一个工具栏。用户选择文本框内的文本并从工具栏更改字体大小。我想要更改所选文本的样式。

我已经搜索过了,但是找不到任何有用的DJ示例。 - Saber Amani
真的吗,好的,你想做什么,而在网上找不到呢?也许你应该更新你的问题,并给出一个确切的例子,说明你想要做什么。 - MethodMan
希望这足以让你开始了。 - MethodMan
谢谢DJ :D 是的,这已经足够了。 - Saber Amani
太棒了,Saber。很高兴我能帮上忙。 - MethodMan
2个回答

9

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();
    }

以下是一些例子 Windows 更改字体和字体颜色(不是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!";
}

5
没有名为SelectionFont或SelectionColor的属性,这是WPF中的一个特性。 - Saber Amani
我会修改我的回答,等一下。 - MethodMan

2
对于 WPF RichTextBox,您必须使用 ApplyPropertyValue 方法应用于 TextRange。您可以通过 RichTextBox 实例的 Selected 属性获取所选的 TextRange。
var selection = myRichTextBox.Selection;
if (!selection.IsEmpty)
    selection.ApplyPropertyValue(TextElement.FontSizeProperty, 10.0);

这是一个WPF应用程序,而不是WinForm。 - Saber Amani

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接