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>
Here's an extension of H.B.'s idea that works with both text and images.
I found that difference is always >4 whenever the RTB has text. However, if you only paste an image it is 3. To combat this i look at the string length of the raw rtf string.
var start = Document.ContentStart;
var end = Document.ContentEnd;
var difference = start.GetOffsetToPosition(end);
HasText = difference > 4 || GetRtfText().Length > 350;
public string GetRtfText()
{
var tr = new TextRange(Document.ContentStart, Document.ContentEnd);
using (var ms = new MemoryStream())
{
tr.Save(ms, DataFormats.Rtf);
return Encoding.Default.GetString(ms.ToArray());
}
}
Through my testing i found that an empty box with no chars has a length of 270. If i even paste in an image that's only 1 pixel in size it balloons to 406.
I played with toggling on various formatting options without typing any letters and haven't gotten close to 300, so I went with 350 for the baseline.
The length check could be expensive if there are no textual characters, but they pasted in a massive image.