gpt4 book ai didi

c# - RichTextBox C# 以编程方式触发某些功能

转载 作者:行者123 更新时间:2023-11-30 21:13:08 24 4
gpt4 key购买 nike

我想在我的 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 上当前选定的文本:


AlignLeft
AlignRight
Center
Increase/Decrease line spacing
Bold
Underline
Italic

最佳答案

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

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

通过 RichTextBox.Document.Blocks 属性,您可以获得一组 block ,这些 block 可以转换为段落。下面是对第一段应用一些样式的代码示例。

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

关于c# - RichTextBox C# 以编程方式触发某些功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7013315/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com