RichTextBox C# 以编程方式触发某些功能 [英] RichTextBox C# programmatically trigger certain functions
问题描述
我想在 RichTextBox 编辑器中以编程方式触发以下函数.
I want to trigger the following functions programmatically in my RichTextBox Editor.
我已经有了:
//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 上当前选定的文本:
I want to apply the following to the currently selected text on a RichTextBox:
左对齐
右对齐
中心
增加/减少行距
粗体
下划线
斜体
AlignLeft
AlignRight
Center
Increase/Decrease line spacing
Bold
Underline
Italic
推荐答案
事实证明,有两种方法可以设置 RichTextBox
的文本样式.
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.
您可以通过 RichTextBox
的 .Document.Blocks
属性获得可以转换为段落的块集合.这是对第一段应用一些样式的代码示例.
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);
请务必始终将正确的类型传递给 ApplyPropertyValue 函数,因为它不支持编译时类型检查.
例如,如果 LineHeightProperty 设置为 45
,这是一个 Int32
,而不是预期的 Double
,您将得到一个运行时ArgumentException
.
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
.
这篇关于RichTextBox C# 以编程方式触发某些功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!