开发者

RichTextBox C# programmatically trigger certain functions

I want to trigger the following functions programmatically in my RichTextBox Editor.

I have this already:

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

I want to apply the following to the currently selected text on a RichTextBox:

AlignLeft

AlignRight

Center

Increase/Decrease line spacing

Bold

Underline

Italic


As it turns out, there are two ways to set a RichTextBox's text styles.

One of them is by changing styles of the control's paragraphs. This only works on paragraphs - not selections.

You get at a collection of blocks, which can be casted to paragraphs, through the .Document.Blocks property of the RichTextBox. Here's a code sample that applies some styling to the first paragraph.

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;

When possible, this is the preferred way of applying styles. Although it does require you to write more code, it provides compile-time type checking.

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

This permits you to apply styles to a selection, but is not type-checked.

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

Be very careful to always pass correct types to the ApplyPropertyValue function, as it does not support compile-time type checking.

For instance, if the LineHeightProperty were set to 45, which is an Int32, instead of the expected Double, you will get a run-time ArgumentException.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜