Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I undo a TextBox's text changes caused by a binding?

I have a TextBox to which i bound a string, if i now edit the text manually i will be able to undo those changes via TextBox.Undo(), if however i change the string and the TextBox's text is updated, i cannot undo those changes and the TextBox.CanUndo property will always be false.
I suppose this might have to do with the complete replacement of the text rather than a modification of it.

Any ideas on how i can get this to work?

like image 329
H.B. Avatar asked Dec 18 '10 02:12

H.B.


1 Answers

I was facing the same issue (needed to accept input upon Enter and revert to original value upon Escape) and was able to handle it this way:

  1. Set UpdateSourceTrigger of your TextBox.Text binding to Explicit.
  2. Handle KeyDown event of your TextBox and put the following code in there:

    if (e.Key == Key.Enter || e.Key == Key.Escape)
    {
      BindingExpression be = ((TextBox)sender).GetBindingExpression(TextBox.TextProperty);
    
      if (e.Key == Key.Enter)
      {
        if (be != null) be.UpdateSource();
      }
      else if (e.Key == Key.Escape)
      {
        if (be != null) be.UpdateTarget(); //cancels newly supplied value and reverts to the original value
      }
    }
    

I found this solution to be very elegant because it can be used in DataTemplates too. For example in my case I used it to allow in-place editing of ListBox items.

like image 150
dotNET Avatar answered Oct 05 '22 23:10

dotNET