[英]C# WPF RichTextboxf check if there is any Text
我不想检查RichTextbox的内容,如果它是空的,则更好。 我通过代码调试,发现在我从框中得到的字符串中有“\\ r \\ n”。 我怎样才能检查这个,因为只是String.Equals("\\r\\n");
不行。 为了从RichTextbox中获取文本,我有这个方法:
private string ConvertRichTextBoxContentsToString(RichTextBox rtb)
{
TextRange textRange = new TextRange(rtb.Document.ContentStart,
rtb.Document.ContentEnd);
return textRange.Text;
}
有人对此有所了解吗?
\\ r \\ n是CRLF新行字符
你试过.IsEmpty属性吗? https://msdn.microsoft.com/en-us/library/system.windows.documents.textrange.isempty(v=vs.110).aspx
尝试这个:
if(String.IsNullOrWhiteSpace(text))
{
// Text found
}
else
{
// No text
}
你也可以用text.Trim()
摆脱whitspace和新行。
string.IsNullOrWhiteSpace
应该实际工作。 尝试这个:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
string s = ConvertRichTextBoxContentsToString(rtb);
if (string.IsNullOrWhiteSpace(s))
{
MessageBox.Show("empty!");
}
}
}
<RichTextBox x:Name="rtb" />
这也有效:
string s = ConvertRichTextBoxContentsToString(rtb);
if(s == "\r\n")
{
MessageBox.Show("empty!");
}
并且相等:
string s = ConvertRichTextBoxContentsToString(rtb);
if (s.Equals("\r\n"))
{
MessageBox.Show("empty!");
}
如果您没有看到MessageBox,则RichTextBox不是真正的空。 你可能想读这个:
如果输入并删除了内容,则开始和结束指针之间的差异为4.您可以尝试使用上面的以下方法来确定RichTextBox是否为空:
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.