2014-12-31 3 views
-1

WPF의 서식있는 텍스트 상자에서 단락을 읽고이를 메시지 상자에 표시하려면 어떻게해야합니까?리치 텍스트 단락에서 단락 읽기

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

과 함께이를 넣어하는 방법의 예 것은 :

,536,
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에 하위 항목에 대한 정의가 없습니다. – GunJack

+0

@GunJack -'DependencyObjectExtensions' 정적 클래스는'DependencyObject'에'Descendants()'라는 [확장 메소드'] (http://msdn.microsoft.com/en-us/library/bb383977.aspx)를 추가하고 'FlowDocument'를 포함한 그 모든 서브 클래스. 내 대답에 표시된 두 가지 확장 클래스를 모두 포함 했습니까? – dbc

관련 문제