Detect if a RichTextBox is empty

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

    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;
    }
    

提交回复
热议问题