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?