2017-02-10 33 views
0

C# WPF,我有一個函數從flowdocumentreader檢索文本:(C#WPF) 「TextPointer.GetTextInRun」 方法忽略類似的字符爲 「 r n」 個

static string GetText(TextPointer textStart, TextPointer textEnd) 
{ 
    StringBuilder output = new StringBuilder(); 
    TextPointer tp = textStart; 
    while (tp != null && tp.CompareTo(textEnd) < 0) 
    { 
     if (tp.GetPointerContext(LogicalDirection.Forward) == 
     TextPointerContext.Text) 
     { 
      output.Append(tp.GetTextInRun(LogicalDirection.Forward)); 
     } 
      tp = tp.GetNextContextPosition(LogicalDirection.Forward); 
    } 
    return output.ToString(); 
} 

然後,我使用的功能如下:

string test = GetText(rtb.Document.ContentStart, rtb.Document.ContentEnd); 

但是,字符串"test"忽略所有的換行,這意味着"\r\n"。它確實保留了製表符,"\t"

我的問題是如何保持所有的換行符?我想自動突出每個段落的第一句,所以我需要檢測換行符"\r\n"

提前感謝您的時間。

更新: 我的.RTF文件加載到flowdocumentreader這樣的:

  if (dlg.FileName.LastIndexOf(".rtf") != -1) 
      { 
       paraBodyText.Inlines.Clear(); 
       string temp = File.ReadAllText(dlg.FileName, Encoding.UTF8); 
       MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(temp)); 
       TextRange textRange = new TextRange(flow.ContentStart, flow.ContentEnd); 

       textRange.Load(stream, DataFormats.Rtf); 
       myDocumentReader.Document = flow; 

       stream.Close(); 
      } 
+0

您沒有使用TextRang的任何特定原因è? – Ron

+0

@Ramin你能告訴我如何使用TextRange來解決問題嗎?我是C#的新手。謝謝。 –

回答

0

編輯

假設每個段落都有至少一個句子以點結束,你可以使用下面的代碼使第一句粗體:

 List<TextRange> ranges = new List<TextRange>(); 
     foreach (Paragraph p in rtb.Document.Blocks.OfType<Paragraph>()) 
     { 
      TextPointer pointer = null; 
      foreach (Run r in p.Inlines.OfType<Run>()) 
      { 
       int index = r.Text.IndexOf("."); 
       if (index != -1) 
       { 
        pointer = r.ContentStart.GetPositionAtOffset(index); 
       } 
      } 
      if (pointer == null) 
       continue; 

      var firsSentence = new TextRange(p.ContentStart, pointer); 
      ranges.Add(firsSentence); 

     } 
     foreach (var r in ranges) 
     { 
      r.ApplyPropertyValue(TextElement.FontWeightProperty, FontWeights.Bold); 
     } 
+0

正如我在我的問題中所述,我想要得到每個段落的第一句話。通過使用TextRange可以實現嗎?謝謝。 –

+0

@KaKaShi_CantAim你的意思是你想改變從段落開始到第一個點(。)的字體重量? – Ron

+0

@KaKaShi_CantAim請參閱編輯。 – Ron