Silverlight RichtTextBox ContentStart & ContentEnd
On the MSDN site, I开发者_StackOverflow found a method, which checks to see if a Silverlight RichTextBox usercontrol is empty or not.
Link: http://msdn.microsoft.com/en-us/library/system.windows.controls.richtextbox.contentstart%28v=vs.95%29.aspx
Method:
public bool isRichTextBoxEmpty()
{
TextPointer startPointer = myRichTextBox.ContentStart.GetNextInsertionPosition(LogicalDirection.Forward);
TextPointer endPointer = myRichTextBox.ContentEnd.GetNextInsertionPosition(LogicalDirection.Backward);
if (startPointer.CompareTo(endPointer) == 0) {
return true;
}
else {
return false;
}
}
However, if the RichTextBox is actually empty, this crashes the Silverlight App. No TextPointers were returned and thus the 2 variables are filled with null.
What I did to clear the RichTextBox is use a button which executes this:
if(!isRichTextBoxEmpty()) {
myRichTextBox.Blocks.Clear();
}
With that exact function. So if there is text, it does work. If there is non, I get null-references. What is happening here?
Working in Silverlight 4.0
You need at least one block for the method to work.
I would add the following line at the beginning of the method:
if (myRichTextBox.Blocks.Count == 0) return true;
The method in its original form is not safe, it's even rather redundant as it uses
if (startPointer.CompareTo(endPointer) == 0)
return true;
else
return false;
instead of
return startPointer.CompareTo(endPointer) == 0;
(The camelCase method name seems fishy to me as well)
精彩评论