Detect if a RichTextBox is empty

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

    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:

        Private Function RichTextBoxIsEmpty(BYVAL rtb As RichTextBox) As Boolean
    
        Dim ReturnCode As Boolean = True
    
        Dim text As String = New TextRange(rtb.Document.ContentStart, rtb.Document.ContentEnd).Text
    
        If String.IsNullOrWhiteSpace(text) Then
    
            For Each block As Block In rtb.Document.Blocks
    
                'check for an image
                If TypeOf block Is Paragraph Then
                    Dim paragraph As Paragraph = DirectCast(block, Paragraph)
                    For Each inline As Inline In paragraph.Inlines
                        If TypeOf inline Is InlineUIContainer Then
                            Dim uiContainer As InlineUIContainer = DirectCast(inline, InlineUIContainer)
                            If TypeOf uiContainer.Child Is Image Then
                                ReturnCode = False
                                Exit For
                            End If
                        End If
                    Next
                End If
    
                ' Check for a table
                If TypeOf block Is Table Then
                    ReturnCode = False
                    Exit For
                End If
    
            Next
    
        Else
    
            ReturnCode = False
    
        End If
    
        Return ReturnCode
    
    End Function
    

    there may be other checks to do, but this at least covers text, images and tables.

提交回复
热议问题