Question: From the above WPF RichTextBox
, how can we programmatically get the list shown above?
Details: Using following Extension Methods, I can read all paragraphs from the above RichTextBox
. The btnTest_Click(...)
event (code shown below) returns all the paragraphs as follows (as you may have guessed from the above image), each line is a paragraph. But below code does not tell me which object (element) is a list:
Output of btnTest_Click(...) event:
This is a test.
Following is a list number:
1. Item 1
2. Item 2
3. Item 3
End of test.
MainWindow.xaml:
.....
<RichTextBox x:Name="rtbTest" AcceptsTab="True" FontFamily="Calibri"/>
.....
File1.cs:
using System.Windows.Documents;
using System.Linq;
namespace MyProjectName
{
public static class FlowDocumentExtensions
{
public static IEnumerable<Paragraph> Paragraphs(this FlowDocument doc)
{
return doc.Descendants().OfType<Paragraph>();
}
}
}
File2.cs:
using System.Windows;
using System.Linq;
namespace MyProjectName
{
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;
}
}
}
Code to read all paragraphs:
private void btnTest_Click(object sender, RoutedEventArgs e)
{
foreach (Paragraph paragraph in rtbTest.Document.Paragraphs())
{
System.System.Diagnostics.Debug.WriteLine(new TextRange(paragraph.ContentStart, paragraph.ContentEnd).Text);
}
}