Search code examples
c#wpfwpf-controls

determine a textbox's previous value in its lost focused event? WPF


I have a textbox and have an onlostfocus event on it.

Inside the lostfocus method, is there a way I can determine if the user has actually changed the value in it? i.e how do i get hold of any previous value in it?

Thanks


Solution

  • What comes to mind for me is a two stage approach. Handle the TextChanged event on the textbox and flag it. Then when the textbox OnLostFocus occurs you can simply check your flag to see if the text has been changed.

    Here is a code snippet on how you could handle the 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;
            }              
        }
    }