gpt4 book ai didi

c# - 在 RichTextBox C# WPF 中设置插入符位置

转载 作者:太空宇宙 更新时间:2023-11-03 21:13:31 26 4
gpt4 key购买 nike

我有一个带有 Name = EditorRichTextBox!以及以下代码:

 String textRich = new TextRange(Editor.Document.ContentStart, Editor.Document.ContentEnd).Text;           
EditorColor ec = new EditorColor(textRich);//Transform The text in RTF Text
Stream stream = new MemoryStream(ASCIIEncoding.Default.GetBytes(ec.SetText())); //SetText Function return a RTF text
Editor.Selection.Select(Editor.Document.ContentStart, Editor.Document.ContentEnd);
Editor.Document.Blocks.Clear();
Editor.Selection.Load(stream, DataFormats.Rtf);//Change the text with the RTF Text
Editor.CaretPosition = ????

我想将 Editor.CaretPosition 设置为选择和更改文本之前的状态?在这里不起作用:

 TextPointer carret = Editor.CaretPosition;
do above code ......
Editor.CaretPosition = carret; // it sets the carret at end of Richtextbox

那么怎么做呢?

最佳答案

如果您的纯文本转换为格式化文本,这应该有效:

 // Save the current position
int caretIntPosition = GetIntPosition(Editor.CaretPosition, Editor);

// Do your work ...

// Restore the position
SetIntPosition(caretIntPosition, Editor);

/// <summary>
/// Converts a TextPointer position into an int position.
/// </summary>
int GetIntPosition(TextPointer pointerPosition, RichTextBox rtb)
{
int intPosition = 0;

TextPointer currentPosition = rtb.Document.ContentStart;

while (currentPosition.CompareTo(pointerPosition) != 0)
{
intPosition++;

currentPosition = currentPosition.GetNextInsertionPosition(LogicalDirection.Forward);
}

return intPosition;
}

/// <summary>
/// Converts an int position back into a TextPointer position and places the caret there.
/// </summary>
void SetIntPosition(int intPosition, RichTextBox rtb)
{
TextPointer currentPosition = rtb.Document.ContentStart;

for (int i = 1; i <= intPosition; i++)
{
currentPosition = currentPosition.GetNextInsertionPosition(LogicalDirection.Forward);
}

rtb.CaretPosition = currentPosition;
}

关于c# - 在 RichTextBox C# WPF 中设置插入符位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36086944/

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