2010-07-19 99 views
1

我想在我的FlowDocumentScrollViewer中選擇文本。WPF FlowDocumentScrollViewer Selection.Select不工作

我能找到TextPointer的開始位置和結束位置。所以我有2個TextPointers ...

TextPointer startPos; 
TextPointer endPos; 

使用這2個TextPointers我試圖在我的FlowDocumentScrollViewer中選擇文本。我正在這樣做...

flowDocumentScrollViewer.Selection.Select(startPos, endPos); 

我希望這會突出顯示選定的文本。但它並沒有這樣做。

爲什麼這不起作用???

[更新] 這是我如何得到TextPointers:

TextPointer pointer = flowDocument.Document.ContentStart; 
while (pointer != null) 
{ 
    if (pointer.GetPointerContext(LogicalDirection.Forward) == TextPointerContext.Text) 
    { 
    string textRun = pointer.GetTextInRun(LogicalDirection.Forward); 
    // where textRun is the text in the flowDocument 
    // and searchText is the text that is being searched for 
    int indexInRun = textRun.IndexOf(searchText); 
    if (indexInRun >= 0) 
    { 
     TextPointer startPos = pointer.GetPositionAtOffset(indexInRun); 
     TextPointer endPos = pointer.GetPositionAtOffset(indexInRun + searchText.Length); 
    } 
    } 
    pointer = pointer.GetNextContextPosition(LogicalDirection.Forward); 
} 

回答

1

我從TextRange.Select方法的MSDN文檔複製下面的代碼,用FlowDocumentScrollViewer取代RichTextBox的,它按預期工作。你是如何定義你的TextPointers的? 似乎是您的問題最可能的原因。

更新:我更新了我的代碼以包含您的選擇算法,它仍然有效。我知道唯一不同的是選擇後的「休息」。否則,它會從searchText的第一次出現開始直到最後一次出現的結束。除此之外,我可以想象你的searchText可能不會被包含在你的文檔中(可能是一個套管問題?),但這只是猜測。你調試了你的代碼嗎?當您嘗試選擇文本時,TextPointers是否有效(不爲空等)?

XAML:

<FlowDocumentScrollViewer GotMouseCapture="richTB_GotMouseCapture" Name="richTB"> 
    <FlowDocument> 
     <Paragraph Name="myParagraph"> 
      <Run> 
       When the user clicks in the RichTextBox, the selected text changes programmatically. 
      </Run> 
     </Paragraph> 
    </FlowDocument> 
</FlowDocumentScrollViewer> 

代碼:

private void richTB_GotMouseCapture(object sender, MouseEventArgs e) 
{ 
    string searchText = "text"; 
    TextPointer pointer = richTB.Document.ContentStart; 
    while (pointer != null) 
    { 
     if (pointer.GetPointerContext(LogicalDirection.Forward) == TextPointerContext.Text) 
     { 
      string textRun = pointer.GetTextInRun(LogicalDirection.Forward); 
      // where textRun is the text in the flowDocument 
      // and searchText is the text that is being searched for 
      int indexInRun = textRun.IndexOf(searchText); 
      if (indexInRun >= 0) 
      { 
       TextPointer startPos = pointer.GetPositionAtOffset(indexInRun); 
       TextPointer endPos = pointer.GetPositionAtOffset(indexInRun + searchText.Length); 
       richTB.Selection.Select(startPos, endPos); 
       break; 
      } 
     } 
     pointer = pointer.GetNextContextPosition(LogicalDirection.Forward); 
    } 
} 
+0

感謝您的幫助。看到我上面的編輯。你看到這個代碼有問題嗎? – dcinadr 2010-07-19 17:57:34

+0

更新了我的答案,以包含您的選擇算法。 – andyp 2010-07-19 19:32:38

+0

其實我在你做的同一個地方有「休息」。我正在搜索的文本確實包含在文檔中。當我調試它找到搜索文本並創建非空的TextPointers。我真正看到的唯一區別是您正在執行GotMouseCapture事件中的代碼。我的活動正在被其他用戶控件觸發。但我不明白爲什麼這會是一個問題,只要我能夠正確引用FlowDocumentScrollViewer? – dcinadr 2010-07-19 20:14:12