-2

I have a simple example using a TextBox and TextBlock in WPF to demonstrate two-way binding, but so far it's not working.

Here's the XAML:

<Grid>
    <StackPanel>
        <TextBox Text="{Binding Path=p_firstValue, Mode=TwoWay}" />
        <TextBlock Text="{Binding Path=p_secondValue}"/>
    </StackPanel>
</Grid>

And here's the C#:

    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            DataContext = new Controller();
        }
    }

    internal class Controller : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler? PropertyChanged;

        private int firstValue = 0;
        public int p_firstValue
        {
            get { return firstValue; }
            set
            {
                firstValue = value;
                SetSecondValue();
            }
        }

        private int secondValue;
        public int p_secondValue
        {
            get { return secondValue; }
            set { secondValue = value; }
        }

        public void SetSecondValue()
        {
            p_secondValue = firstValue * 2;
            RaisePropertyChanged("p_secondValue");
        }

        public void RaisePropertyChanged(string property)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(property));
            }
        }
    }

My expectation is that the second value will visually changed as I type, but it's not working with the binding alone.

I got a version of this working by binding the TextBox's TextChanged to a handler function that parses the string to make sure it's numeric and then calls SetSecondValue() in the controller directly.

I don't feel like I should have to do all that extra work, though, since Mode=TwoWay is set. What am I missing here?

Nightmare Games
  • 2,205
  • 6
  • 28
  • 46
  • 1
    [Binding.UpdateSourceTrigger](https://learn.microsoft.com/en-us/dotnet/api/system.windows.data.binding.updatesourcetrigger?view=windowsdesktop-7.0) – Sir Rufo Jul 01 '23 at 03:32

1 Answers1

-1

I needed to add UpdateSourceTrigger=PropertyChanged to my xaml binding. Now it works.

Nightmare Games
  • 2,205
  • 6
  • 28
  • 46