What is the best way to detect if a WPF RichTextBox/FlowDocument is empty?
The following works if only text is present in the document. Not if it contains UIElement\'s>
You could compare the pointers, which is not all too reliable:
var start = rtb.Document.ContentStart;
var end = rtb.Document.ContentEnd;
int difference = start.GetOffsetToPosition(end);
This evaluates to 2
if the RTB is loaded, and 4
if content has been entered and removed again.
If the RTB is completely cleared out e.g. via select all -> delete
the value will be 0
.
In the Silverlight reference on MSDN another method is found which can be adapted and improved to:
public bool IsRichTextBoxEmpty(RichTextBox rtb)
{
if (rtb.Document.Blocks.Count == 0) return true;
TextPointer startPointer = rtb.Document.ContentStart.GetNextInsertionPosition(LogicalDirection.Forward);
TextPointer endPointer = rtb.Document.ContentEnd.GetNextInsertionPosition(LogicalDirection.Backward);
return startPointer.CompareTo(endPointer) == 0;
}