RichTextBox C# programmatically trigger certain functions

倾然丶 夕夏残阳落幕 提交于 2019-12-11 03:38:37

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/7013315/richtextbox-c-sharp-programmatically-trigger-certain-functions

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!