abdou31
abdou31

Reputation: 75

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:

How can I do this?

Upvotes: 0

Views: 273

Answers (1)

Arkane
Arkane

Reputation: 420

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.

Upvotes: 1

Related Questions