TextBlock.GetPositionFromPoint raises NullReferenceException
The TextBlock.GetPositionFromPoint
raises a NullReferenceException
in some cases. This method should return a TextPointer to the text that starts at the given position. In some cases it generates a NullReferenceException
instead, which is clearly a bug. The internals of this method looks like:
public TextPointer GetPositionFromPoint(Point point, bool snapToText)
{
if (this.CheckFlags(Flags.ContentChangeInProgress))
throw new InvalidOperationException(SR.Get("TextContainerChangingReentrancyInvalid"));
if (((ITextView)this._complexContent.TextView).Validate(point))
return (TextPointer) this._complexContent.TextView.GetTextPositionFromPoint(point, snapToText);
if (snapToText)
return new TextPointer((TextPointer) this._complexContent.TextContainer.Start);
return null
}
The call fails in the TextBlock.GetPositionFromPoint
according to the call-stack. The most obvious error is that the _complexContent
field isn’t set. After some research, I found out that most methods that rely on this field call TextBlock.EnsureComplexContent()
first. This has been neglected in the TextBlock.GetPositionFromPoint
method. We cannot call TextBlock.EnsureComplexContent
from usercode, because it is a private method. You can get the ContentStart
or ContentEnd
properties, which will call TextBlock.EnsureComplexContent
.
...
var dummy = this.myTextBox.ContentStart; // WORKAROUND
TextPointer start = this.myTextBox.GetPositionFromPoint(selection.TopLeft, true);
...
Conclusion
This bug should be fixed by Microsoft by adding a call to EnsureComplexContent
before it accesses the _complexContent
field. It’s fairly easy to prevent the exception, but it might have took you some time to find out about the error and get to this blog.
Response from Microsoft
I have submitted this bug to Microsoft and it is filed under feedback item #478575. Microsoft confirmed it is a bug and it will be fixed when .NET Framework 4 will hit RTM (the current beta still has the bug).