C# - 从富文本框中读取段落

时间:2014-12-31 05:32:59

标签: c# wpf richtextbox

如何从WPF中的富文本框中读取段落并将其显示在消息框中?

1 个答案:

答案 0 :(得分: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);
    }