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?
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:
UpdateSourceTrigger
of your TextBox.Text
binding to Explicit
.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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With