检测 RichTextBox 是否为空 [英] Detect if a RichTextBox is empty

查看:78
本文介绍了检测 RichTextBox 是否为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

What is the best way to detect if a WPF RichTextBox/FlowDocument is empty?

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

The following works if only text is present in the document. Not if it contains UIElement's

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

推荐答案

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

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

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

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.

MSDN 上的 Silverlight 参考

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

这篇关于检测 RichTextBox 是否为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆