キャレットの相対位置を保存して復元するには、GetOffsetToPosition()
とGetPositionAtOffset()
を使用できます。リッチテキストボックスは次のように初期化することを想定しつまり
、:
RichTextBox rtb;
int paragraphIndex = -1;
int indexInParagraph;
public MainWindow()
{
InitializeComponent();
rtb = new RichTextBox();
rtb.Document = new FlowDocument();
Paragraph para = new Paragraph(new Run("some text some text some text."));
rtb.Document.Blocks.Add(para);
// sets the caret at a specific (random) position in the paragraph:
rtb.CaretPosition = para.ContentStart.GetPositionAtOffset(5);
this.Content = rtb;
}
は、クラスで3つのprivateフィールドに注意してください。
あなたはテキストを交換する前に、段落でキャレットの段落のインデックスとキャレットのインデックスを保存する必要があります。
public void SaveCaretState()
{
//enumerate and get the paragraph index
paragraphIndex = -1;
foreach (var p in rtb.Document.Blocks)
{
paragraphIndex++;
if (p == rtb.CaretPosition.Paragraph)
break;
}
//get index relative to the start of the paragraph:
indexInParagraph = rtb.CaretPosition.Paragraph.ElementStart.GetOffsetToPosition(rtb.CaretPosition);
}
を、あなたが言ったときにそれを復元:
public void RestoreCaretState(MouseEventArgs e)
{
// you might need to insure some conditions here (paragraph should exist and ...)
Paragraph para = rtb.Document.Blocks.ElementAt(paragraphIndex) as Paragraph;
rtb.CaretPosition = para.ElementStart.GetPositionAtOffset(indexInParagraph);
}
をそのAということに注意してください単純な例であり、他のBlock
がRichTextBox.Document
に存在する可能性があります。しかし、アイデアと実装はそれほど違いはありません。
出典
2017-03-06 01:14:41
Ron
ありがとうございました。これが助けになりました。私はある位置をブロックと見なして位置を認識するので、ブロックを追加すると+ =の位置はブロック全体をスキップできますが、それを理解することができます。ご協力いただきありがとうございます。 – user6590430