Detect if a RichTextBox is empty

后端 未结 5 2747
时光取名叫无心
时光取名叫无心 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 02:15

    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.

提交回复
热议问题