tags:

views:

332

answers:

1

Hello.

Hi! I am trying to cancel (prevent) some text editing in RichTextBox. I am using TextChanged event, but I did not find the way how to cancel or rollback some changes, any ideas?

private void mainRTB_TextChanged(object sender, TextChangedEventArgs e)
        {
            TextRange text = new TextRange(mainRTB.Document.ContentStart, mainRTB.Document.ContentEnd);
            if (text.Text.Length >= this.MaxLenght)
            {
                mainRTB.Document.ContentEnd.DeleteTextInRun(-1);
                mainRTB.IsReadOnly = true;
            }
}

By executing mainRTB.Document.ContentEnd.DeleteTextInRun(-1); does not delete any text.

mainRTB -> System.Windows.Controls.RichTextBox

Thks

+1  A: 

I do not believe there is a way to prevent the edit because there is only a ChangedEvent and no Changing or PreviewChange event. What you could try though is undoing the change.

private void mainRTB_TextChanged(object sender, TextChangedEventArgs e)  {
            TextRange text = new TextRange(mainRTB.Document.ContentStart, mainRTB.Document.ContentEnd);
            if (text.Text.Length >= this.MaxLenght && mainRTB.CanUndo)
            {
                mainRTB.Undo();
                mainRTB.IsReadOnly = true;
            }
}
JaredPar
With the Undo operation all text that I have entered is deleted. If I press the "aaaaaaa" in just one time the Undo operation will be: delete all "aaaaaa" that I have entered. Thus, all text is deleted.This is not what I want, gives stranges behaviours.What is the main purpose of DeleteTextInRun
rpf