Determine the previous value of a text field in its lost focused event? WPF

I have a text box and there is an onlostfocus event on it.

Inside the lostfocus method, is there a way to determine if the user has really changed the value in it? How can I get any previous value?

thank

+3
source share
4 answers

What comes to mind for me is a two-step approach. Process the event TextChangedin the text box and mark it. Then, when the text box appears OnLostFocus, you can simply check your flag to see if the text has been changed.

Here is a snippet of code on how you can handle tracking.

public class MyView
{
    private bool _textChanged = false;
    private String _oldValue = String.Empty;

    TextChanged( ... )
    {
        // The user modifed the text, set our flag
        _textChanged = true;        
    } 

    OnLostFocus( ... )
    {
        // Has the text changed?
        if( _textChanged )
        {
            // Do work with _oldValue and the 
            // current value of the textbox          

            // Finished work save the new value as old
            _oldValue = myTextBox.Text;

            // Reset changed flag
            _textChanged = false;
        }              
    }
}
+2

WPF, , .

. , , LostFocus. , , .

XAML :

<TextBox Text="{Binding MyProperty, Mode=TwoWay}"/>

:

private string _MyProperty;

public string MyProperty
{
   get { return _MyProperty; }
   set
   {
      // at this point, value contains what the user just typed, and 
      // _MyProperty contains the property previous value.
      if (value != _MyProperty)
      {
         _MyProperty = value;
         // assuming you've implemented INotifyPropertyChanged in the usual way...
         OnPropertyChanged("MyProperty"); 
      }
   }
+5

-. , , , , . ASP.NET, .

0

Another way to solve this is by binding the data: Bind TextBox.Text to the property that contains the inital value, but use the binding with UpdateSourceTrigger=Explicit Then, when the text field loses focus, you can check the binding if the source and target values ​​are different using this code fragment and evaluation of the resulting BindingExpression: BindingExpression be = tb.GetBindingExpression(TextBox.TextProperty); Another code can be found here: http://bea.stollnitz.com/blog/?p=41

0
source

Source: https://habr.com/ru/post/1755754/


All Articles