【问题标题】:RichTextBox C# programmatically trigger certain functionsRichTextBox C# 以编程方式触发某些功能
【发布时间】:2011-08-10 15:20:31
【问题描述】:

我想在我的 RichTextBox 编辑器中以编程方式触发以下函数。

我已经有了这个:

//Copy   
TextRange range = new TextRange(doc.Editor.Selection.Start, doc.Editor.Selection.End);
                Clipboard.SetText(range.Text);
    //Paste  
     Editor.Paste();
   // PageDown 
     Editor.PageDown();
   // PageUp     
     Editor.PageUp();
    //Text Size 
     Editor.FontSize = number;
    //Undo    
     Editor.Undo();
    //Redo    
     Editor.Redo();

我想将以下内容应用于 RichTextBox 上当前选定的文本:


左对齐
右对齐
中心
增加/减少行距
粗体
下划线
斜体

【问题讨论】:

  • 您要加粗/斜体/下划线/等选定文本、所有文本还是您将要输入的任何文本?
  • @Vladislav 选定文本
  • 我已经扩展了我的答案,将缺失的样式应用于 TextRange。希望这会有所帮助。

标签: c# wpf richtextbox


【解决方案1】:

事实证明,有两种方法可以设置RichTextBox 的文本样式。

其中之一是更改控件段落的样式。这仅适用于段落 - 不适用于选择。

您可以通过RichTextBox.Document.Blocks 属性获得一组可以转换为段落的块。这是一个将一些样式应用于第一段的代码示例。

Paragraph firstParagraph = Editor.Document.Blocks.FirstBlock as Paragraph;
firstParagraph.TextAlignment = TextAlignment.Right;
firstParagraph.TextAlignment = TextAlignment.Left;
firstParagraph.FontWeight = FontWeights.Bold;
firstParagraph.FontStyle = FontStyles.Italic;
firstParagraph.TextDecorations = TextDecorations.Underline;
firstParagraph.TextIndent = 10;
firstParagraph.LineHeight = 20;

如果可能,这是应用样式的首选方式。虽然它确实需要您编写更多代码,但它提供了编译时类型检查。

The other, would be to apply them to a text range

这允许您将样式应用于选择,但不进行类型检查。

TextRange selectionRange = Editor.Selection as TextRange;
selectionRange.ApplyPropertyValue(TextElement.FontWeightProperty, FontWeights.Bold);
selectionRange.ApplyPropertyValue(TextElement.FontStyleProperty, FontStyles.Italic);
selectionRange.ApplyPropertyValue(Inline.TextDecorationsProperty, TextDecorations.Underline);
selectionRange.ApplyPropertyValue(Paragraph.LineHeightProperty, 45.0);
selectionRange.ApplyPropertyValue(Paragraph.TextAlignmentProperty, TextAlignment.Right);

请务必始终将正确的类型传递给 ApplyPropertyValue 函数,因为它不支持编译时类型检查。

例如,如果 LineHeightProperty 设置为45,即Int32,而不是预期的Double,您将获得运行时ArgumentException

【讨论】:

  • 谢谢 :) 下划线的属性是什么?
  • 在所有事物中,它是Inline.TextDecorationsProperty,其值为TextDecorations.Underline
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-12
  • 2010-10-02
  • 1970-01-01
  • 1970-01-01
  • 2014-03-16
相关资源
最近更新 更多