问题
I've spent hours trying to understand what is happening here. I have a RichEditBox that the user can interact with by tapping on it and using the keyboard or by tapping on a couple of buttons that add some characters inside the RichEditBox. This is a method I use:
private void ptrPlus_click(object sender, RoutedEventArgs e)
{
try
{
myRichEditBox.Document.Selection.Text = ">";
myRichEditBox.Document.Selection.SetRange(this.Document.Selection.StartPosition + 1, this.Document.Selection.StartPosition + 1);
}
catch
{
//
}
}
What works:
• If I use only the keyboard to write inside the RichEditBox, it works fine
• If I use only the buttons, like this one, it works fine and the characters gets added inside the RichEditBox
What doesn't work:
• If I tap inside the RichEditBox (to either write inside or, or just to make the keyboard appear, and then tap outside it to close it), and then use the button again to add some characters, it works fine for the first two times I press the button. On the third one, I get a System.AccessViolationException and my app crashes at the
myRichEditBox.Document.Selection.Text = ">";
The app crashes even if that line is inside a try/catch, I don't know why. I tried to check the state of both the Selection index position and the Selection lenght before and after the RichEditBox got focus as I tapped on it, and it doesn't seem that they change in any way. So I don't really know what is happening here :/
Thanks in advance for your help! Sergio
EDIT: I added this handler for the LostFocus event:
void MyRichEditBox_LostFocus(object sender, RoutedEventArgs e)
{
String temp;
int start = this.Document.Selection.StartPosition, end = this.Document.Selection.EndPosition;
this.Document.GetText(TextGetOptions.FormatRtf, out temp);
this.Document.SetText(TextSetOptions.FormatRtf, temp);
this.Document.Selection.SetRange(start, end);
}
This should be rather pointless, but I discovered that it "fixes the error" (even though this shouldn't do anything). The downside is that it adds a new line at the end of the Document, I suspect that's because of the extra \r that the RichEditBox adds by default. Any ideas on why this handler doesn't let the app crash anymore and/or how to get rid of the extra final \r? Thanks!
EDIT2: I stopped the debug inside that method and I discovered that the Rtf String didn't contain \r at the end of it, but it had a series of \par that made the RichEditBox add a new line each time. I tried:
temp = temp.Replace(@"\par", "");
Before the SetSext method, but this just messed up the content of the document, even though it did stop the RichEditBox to add new lines. I'll if I can find a way to remove those \par without ruining the Rtf content.
来源:https://stackoverflow.com/questions/26830799/accessviolationexception-when-setting-the-text-in-a-richeditbox