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>
The event handler is called whenever the contents of the TextBox control are changed, either by a user or programmatically. This event fires when the TextBox control is created and initially populated with text.
Remarks. The TextChanged event is raised when the content of the text box changes between posts to the server. The event is only raised if the text is changed by the user; the event is not raised if the text is changed programmatically.
Creating a TextBoxThe Text property of the TextBox element sets the content of a TextBox. The Name attribute represents the name of the control, which is a unique identifier of a control. The code snippet in Listing 1 creates a TextBox control and sets the name, height, width, and content of a TextBox control.
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}"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With