Search code examples
c#wpfmvvmdata-binding

TextBoxes with TextChange which depend on each other without StackOverflow Exception


I have Two Textboxes which depend on each other on their changes:: Assume: ::IF TextBox1 values changed makes impact to TextBox2 values, and viceversa is true:: Need: When I change TextBox1, i would like to have immediately result on TextBox2

::IF TextBox1 values changed makes impact to TextBox2 values, and viceversa is true::

Example:: CalculatorView.xaml

<TextBox x:Name="TextBox1" Text={Binding Number1, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>

<TextBox x:Name="TextBox2"  Text={Binding Number2, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>

Solution

  • Set the backing field of the other property and raise the PropertyChanged event for it, e.g.:

    public class ViewModel : INotifyPropertyChanged
    {
        private int _number1;
        public int Number1
        {
            get { return _number1; }
            set
            {
                _number1 = value;
                _number2 = 0; //sets the other property to any value...
                OnPropertyChanged();
                OnPropertyChanged(nameof(Number2));
            }
        }
    
        private int _number2;
        public int Number2
        {
            get { return _number2; }
            set
            {
                _number2 = value;
                _number1 = 0; //sets the other property to any value...
                OnPropertyChanged();
                OnPropertyChanged(nameof(Number1));
            }
        }
    
        public event PropertyChangedEventHandler PropertyChanged;
        private void OnPropertyChanged([CallerMemberName] String propertyName = "")
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }