wpf - 检测 RichTextBox 是否为空

标签 wpf richtextbox flowdocument

检测 WPF RichTextBox/FlowDocument 是否为空的最佳方法是什么?

如果文档中仅存在文本,则以下内容有效。不是如果它包含 UIElement 的

new TextRange(Document.ContentStart, Document.ContentEnd).IsEmpty

最佳答案

您可以比较指针,这不太可靠:

var start = rtb.Document.ContentStart;
var end = rtb.Document.ContentEnd;
int difference = start.GetOffsetToPosition(end);

计算结果为 2如果 RTB 已加载,并且 4如果内容已被再次输入和删除。
如果 RTB 被完全清除,例如通过 select all -> delete值将是 0 .

Silverlight reference on MSDN找到了另一种方法,可以对其进行调整和改进:
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;
}

关于wpf - 检测 RichTextBox 是否为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5825575/

相关文章:

调用的目标已抛出 C# 异常

c# - 富文本框内的链接?

c# - WPF : Assigning to RichTextBox. 文档极慢(7 分钟!)

wpf - 如何使用 DocumentViewer 显示流文档?

c# - WPF - 将 UserControl 可见性绑定(bind)到属性

wpf - 如何在使用 Caliburn.Micro 设置的应用程序中设置窗口/应用程序图标

wpf - 如何在 XAML 中的 Style 中设置控件资源字典?

c# - 事件冒泡和 RoutedEventArgs Source 属性

.net - 如何在 FlowDocument 中通过鼠标单击获取 TextPointer

c# - 将 BlockUIContainer 打印到 XpsDocument/FixedDocument