C# - 从富文本框读取段落
本文关键字:读取 段落 文本 | 更新日期: 2023-09-27 18:35:40
如何从 WPF 中的格式文本框中读取段落并将其显示在消息框中?
如果要遍历RichTextBox
中的所有段落,则以下包含扩展方法的静态类提供了必要的方法:
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);
}