So, for example if I have 2 text boxes in WFA. The following code works.
private void textBox1_TextChanged(object sender, EventArgs e)
{
textBox2.Text = textBox1.Text;
}
And I get this. The text in the second text box equals to the text in the first one, when I change it.
But when it comes to WPF, I get a completely different behavior. When I do this.
private void textBox_TextChanged(object sender, TextChangedEventArgs e)
{
textBox1.Text = textBox.Text;
}
And press Ctrl+F5 to test the application, nothing happens. The log says "Build Succeeded" and nothing. What is wrong here?
And here is the XAML code.
<Window x:Class="TextBoxTest.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:TextBoxTest"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Grid>
<TextBox x:Name="textBox" HorizontalAlignment="Left" Height="23" Margin="212,77,0,0" TextWrapping="Wrap" Text="TextBox" VerticalAlignment="Top" Width="120" TextChanged="textBox_TextChanged"/>
<TextBox x:Name="textBox1" HorizontalAlignment="Left" Height="23" Margin="212,124,0,0" TextWrapping="Wrap" Text="TextBox" VerticalAlignment="Top" Width="120"/>
</Grid>
You are encountering a null reference exception. When the textBox
control is created it will trigger the textChange
event on textBox1
and by that point, textBox1
isn't created and is therefore null. You can just change the order of the textboxes in the XAML and you will be fine.
But there is a nicer way of doing this, directly in XAML with Binding:
<TextBox x:Name="textBox" />
<TextBox x:Name="textBox1" Text="{Binding ElementName=textBox, Path=Text}" />
(I excluded some attributes to make the example more clean) Depending on WHEN you want the other textbox to update you can add UpdateSourceTrigger to the binding:
Text="{Binding ElementName=textBox, Path=Text, UpdateSourceTrigger=PropertyChanged}"