C#-从富文本框中读取段落
如何从WPF中的富文本框中读取段落,并将其显示在消息框中?如果您希望遍历WPF中的所有段落,则包含的以下静态类提供了必要的方法:C#-从富文本框中读取段落,c#,wpf,richtextbox,C#,Wpf,Richtextbox,如何从WPF中的富文本框中读取段落,并将其显示在消息框中?如果您希望遍历WPF中的所有段落,则包含的以下静态类提供了必要的方法: public static class FlowDocumentExtensions { public static IEnumerable<Paragraph> Paragraphs(this FlowDocument doc) { return doc.Descendants().OfType<Paragraph&
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;
}
}
如何将这些内容组合在一起的示例是:
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;
}
}
TextRange TextRange=新的TextRange(canvas.Document.ContentStart、canvas.Document.ContentEnd);MessageBox.Show(textRange.Text);但是它给了我盒子里所有的文字把它放在你的问题里好的。让我检查一下,我会告诉你。我该如何处理这些代码。FlowDocument不包含子体的定义。@GunJack-
DependencyObjectExtensions
静态类向DependencyObject
及其所有子类(包括FlowDocument
)添加了一个命名的Substands()
。在我的回答中,你们包括了两个扩展类吗?是的。。很抱歉,我的查询中是否缺少指令或关键字declaration@GunJack-您是否在公共静态IEnumerable子体(此DependencyObject根)的声明中包含此
?
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);
}