Search code examples
c#wpfselectionchanged

Use SelectionChanged event in two textbox , one depend from the other


I have two Textbox and I'm trying to add SelectionChanged Event to the two textbox :

TextBox A => Amount
TextBox B => Summary

The scenario is like :

Two Textbox are empty:

  • The user enter the amount the summary will be equals to 100 * Amount

  • The user enter the summary after clear the field of amount , he should get summary / 100 in the textbox of amount

     private void Amount_SelectionChanged(object sender, RoutedEventArgs e)
      {
          if (!string.IsNullOrEmpty(Amount.Text.ToString()))
          {
              Summary.IsReadOnly = true;
              Summary.Text = (ToDecimalValue(Amount.Text) * 100).ToString();
              Amount.IsReadOnly = false;
    
          }
          else
          {
              Summary.Text = "";
              Summary.IsReadOnly = false;
          }
    
    
      }
    
      private void Summary_SelectionChanged(object sender, RoutedEventArgs e)
      {
          if (!string.IsNullOrEmpty(Summary.Text.ToString()))
          {
              Amount.IsReadOnly = true;
              Amount.Text = (ToDecimalValue(Summary.Text) / 100).ToString()
              Summary.IsReadOnly = false;
    
          }
          else
          {
              Summary.Text = "";
              Summary.IsReadOnly = false;
          }
    
      }
    

How can I do this?


Solution

  • I believe there is a simple solution:

    private bool _isEditing;
    
    private void Amount_TextChanged(object _, RoutedEventArgs __)
    {
        if (_isEditing)
            return;
    
        _isEditing = true;
    
        if (double.TryParse(Amount.Text, out double amount)
            Summary.Text = (amount * 100).ToString();
        else
            Summary.Clear();
    
        _isEditing = false;
    }
    
    private void Summary_TextChanged(object _, RoutedEventArgs __)
    {
        if (_isEditing)
            return;
    
        _isEditing = true;
    
        if (double.TryParse(Summary.Text, out double summary)
            Amount.Text = (summary / 100).ToString();
        else
            Amount.Clear();
    
        _isEditing = false;
    }
    

    Notes:

    • I changed "SelectionChanged" to "TextChanged", as it is the event you want to watch if the user changes the value in the TextBox.
    • I replaced ToDecimalValue() by double.TryParse(), but this will work only if the decimal separator matches that of the application's current culture.
    • _ and __ mean that the parameters are not used.
    • If you want the TextBox to only accepts numbers, see this question.