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
new TextRange(Document.ContentStart, Document.ContentEnd).IsEmpty
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
new TextRange(Document.ContentStart, Document.ContentEnd).IsEmpty
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.
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.
The answer above works if you don't put anything into the RTB. However, if you simply delete the contents, the RTB tends to return a single, empty paragraph, not a completely empty string. So, this is more reliable in such cases:
This only applies to textual contents, of course.
H.B.'s answer isn't useful if you need to distinguish between images and whitespace. You can use something like this answer to check for images.
This seems laborious, and still probably isn't correct for all scenarios. But I couldn't find any better way.
First - thank you to McGarnagle - their answer got me going in the right direction. However for whatever reason their image check didn't work for me. This is what I ended up doing:
there may be other checks to do, but this at least covers text, images and tables.
You could compare the pointers, which is not all too reliable:
This evaluates to
2
if the RTB is loaded, and4
if content has been entered and removed again.If the RTB is completely cleared out e.g. via
select all -> delete
the value will be0
.In the Silverlight reference on MSDN another method is found which can be adapted and improved to: