Detect if a RichTextBox is empty

后端 未结 5 2648
时光取名叫无心
时光取名叫无心 2021-02-20 01:15

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

5条回答
  •  青春惊慌失措
    2021-02-20 01:55

    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.

    bool IsEmpty(Document document)
    {
        string text = new TextRange(Document.ContentStart, Document.ContentEnd).Text;
        if (string.IsNullOrWhiteSpace(text) == false)
            return false;
        else
        {
            if (document.Blocks.OfType()
                .Select(c => c.Child).OfType()
                .Any())
            return false;
        }
        return true;
    }
    

    This seems laborious, and still probably isn't correct for all scenarios. But I couldn't find any better way.

提交回复
热议问题