Text Box Text Changed event in WPF

Roman picture Roman · Nov 8, 2015 · Viewed 43.4k times · Source

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. enter image description here

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>

Answer

ceciliaSHARP picture ceciliaSHARP · Nov 8, 2015

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}"