2017-03-03 28 views
0

我在那裏,我與相同長度的新文本替換文本中的WPF格式文本框控件,我只是想獲得原有插入符位置之前我更換文本,替換文本,然後重置插入位置。嘗試重置在WPF格式文本框控件的光標位置

我覺得現在的問題是,它使用的是綁定到RichTextBox的是,這樣當重新它的位置已經改變復位時,我清楚原文的TextPointer。我真正想要做的是將其重置爲原始文本中的字符位置索引,或者我很樂意處理Lined和Columns。

我已經走遍了互聯網的答案,什麼應該是一個很簡單的問題,似乎沒有任何回答。我真正想要的是一個X/Y座標或任何有用的東西。

回答

0

您可以使用GetOffsetToPosition()GetPositionAtOffset()來保存插入符的相對位置並恢復它。

換句話說,假設RichTextBox的初始化是這樣的:

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; 
    } 

注意班上三個私有字段。

您應該保存插入符號的段落指數和尖指數段落,你替換文本之前:

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); 
    } 

請注意,它是一個簡單的例子,RichTextBox.Document中可能有其他Block。然而,這個想法和實施並沒有太大的不同。

+0

謝謝你的幫助。我注意到一個位置將一個塊視爲一個位置,因此當我添加塊時,+ =的位置可以跳過整個塊,但是我可以計算出該位置。謝謝你的幫助。 – user6590430