2014-12-31 38 views
-1

如何從WPF的富文本框中讀取段落並將其顯示在消息框中?C# - 從富文本框中讀取段落

+0

的TextRange的TextRange =新TextRange(canvas.Document.ContentStart,canvas.Document.ContentEnd); MessageBox.Show(textRange.Text);但它給了我箱中的所有文字 – GunJack

+1

把這個放在你的問題 –

回答

2

如果你想通過所有的段落在RichTextBox迭代,然後含extension methods以下靜態類提供必要的方法:

public static class FlowDocumentExtensions 
{ 
    public static IEnumerable<Paragraph> Paragraphs(this FlowDocument doc) 
    { 
     return doc.Descendants().OfType<Paragraph>(); 
    } 
} 

public static class DependencyObjectExtensions 
{ 
    public static IEnumerable<DependencyObject> Descendants(this DependencyObject root) 
    { 
     if (root == null) 
      yield break; 
     yield return root; 
     foreach (var child in LogicalTreeHelper.GetChildren(root).OfType<DependencyObject>()) 
      foreach (var descendent in child.Descendants()) 
       yield return descendent; 
    } 
} 

一旦你收集到的所有段落在FlowDocument,以轉換單款文本,你可以這樣做:

var text = new TextRange(paragraph.ContentStart, paragraph.ContentEnd).Text; 

和實例如何把這些結合在一起是:

foreach (var paragraph in canvas.Document.Paragraphs()) 
    { 
     MessageBox.Show(new TextRange(paragraph.ContentStart, paragraph.ContentEnd).Text); 
    } 

這就是你想要的嗎?

更新

如果因任何原因,你使用擴展方法是不舒服,你總是可以使用傳統的C#2.0的靜態方法:

public static class FlowDocumentExtensions 
{ 
    public static IEnumerable<Paragraph> Paragraphs(FlowDocument doc) 
    { 
     return DependencyObjectExtensions.Descendants(doc).OfType<Paragraph>(); 
    } 
} 

public static class DependencyObjectExtensions 
{ 
    public static IEnumerable<DependencyObject> Descendants(DependencyObject root) 
    { 
     if (root == null) 
      yield break; 
     yield return root; 
     foreach (var child in LogicalTreeHelper.GetChildren(root).OfType<DependencyObject>()) 
      foreach (var descendent in child.Descendants()) 
       yield return descendent; 
    } 
} 

而且

foreach (var paragraph in FlowDocumentExtensions.Paragraphs(mainRTB.Document)) 
    { 
     MessageBox.Show(new TextRange(paragraph.ContentStart, paragraph.ContentEnd).Text); 
    } 
+0

好的。讓我檢查一下,我會告訴你。 – GunJack

+0

我該如何處理這段代碼。 FlowDocument不包含Descendants的定義。 – GunJack

+0

@GunJack - 「DependencyObjectExtensions」靜態類向'DependencyObject'添加名爲'Descendants()'的['extension method'](http://msdn.microsoft.com/en-us/library/bb383977.aspx)所有的子類,包括'FlowDocument'。你是否在我的答案中包含了兩個擴展類? – dbc