在 RichTextBox 中设置插入符号/光标位置 - WPF [英] Set Caret/Cursor Position in RichTextBox - WPF
问题描述
如何在 WPF 中的 RichTextBox 中设置插入符号/光标位置?
How to set caret/cursor position in RichTextBox in WPF?
我使用 MSDN CaretPosition 但是好像不能设置光标?
I use the code in MSDN CaretPosition but it seems the cursor can't be set?
// Create a new FlowDocument, and add 3 paragraphs.
FlowDocument flowDoc = new FlowDocument();
flowDoc.Blocks.Add(new Paragraph(new Run("Paragraph 1")));
flowDoc.Blocks.Add(new Paragraph(new Run("Paragraph 2")));
flowDoc.Blocks.Add(new Paragraph(new Run("Paragraph 3")));
// Set the FlowDocument to be the content for a new RichTextBox.
RichTextBox rtb = new RichTextBox(flowDoc);
// Get the current caret position.
TextPointer caretPos = rtb.CaretPosition;
// Set the TextPointer to the end of the current document.
caretPos = caretPos.DocumentEnd;
// Specify the new caret position at the end of the current document.
rtb.CaretPosition = caretPos;
推荐答案
如何在 WPF 中的 RichTextBox 中设置插入符号/光标位置?
How to set caret/cursor position in RichTextBox in WPF?
假设 rtb
是您的 RichTextBox 的名称,具有不同的 Blocks and Inlines,可以通过以下方式设置文档开头的Caret:
Assuming thatrtb
is the name of your RichTextBox, with different Blocks and Inlines, you can set the Caret at the beginning of the document by:
rtb.CaretPosition = rtb.CaretPosition.DocumentStart;
或在其末尾:
rtb.CaretPosition = rtb.CaretPosition.DocumentEnd;
另一方面,假设您有一个特定的段落或块,例如:
On the other hand, assuming that you have a specific Paragraph or Block, such as:
Block blk = rtb.Document.Blocks.ElementAt(1);
您可以将插入符号设置为其开头
You can set caret to its start
rtb.CaretPosition = blk.ContentStart;
或者它的结束
rtb.CaretPosition = blk.ContentEnd;
或者如果你有一个特定的内联,比如
or if you have a specific Inline such as
Run r = ((Paragraph)rtb.Document.Blocks.ElementAt(0)).Inlines.ElementAt(1) as Run;
你也可以使用
rtb.CaretPosition = r.ContentStart;
rtb.CaretPosition = r.ContentEnd;
当然,如果您正在处理具有从右到左和从左到右文本的复杂段落,您可能需要考虑
Of course, if you are working with Complex paragraph with both right-to-left and left-to-right text, you might need to consider
rtb.CaretPosition = blk.ElementStart;
rtb.CaretPosition = blk.ElementEnd;
还要注意在 TextPointer
,您可以使用它来访问文档/块/内联的不同部分:
Also note different methods implemented in a TextPointer
, which you can use to reach different parts of the document/Blocks/Inlines:
rtb.CaretPosition = rtb.CaretPosition.GetLineStartPosition(0);
rtb.CaretPosition = rtb.CaretPosition.GetPositionAtOffset(2);
有关更多方法和更多信息,请参阅链接.
See the link for more methods and more information.
最后,您可能希望使用在块或内联中实现的 BringIntoView
方法:
At the end, you might want to use BringIntoView
method implemented in a Block or Inline:
blk.BringIntoView();
r.BringIntoView();
并设置键盘焦点,以查看插入符号的闪烁:
and also setting the keyboard focus, to see the blinking of the Caret:
Keyboard.Focus(rtb);
这篇关于在 RichTextBox 中设置插入符号/光标位置 - WPF的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!