I have two text boxes named txtChange
and txtStatus
. XAML
code is as follows.
<TextBox Height="29" HorizontalAlignment="Left" Margin="418,385,0,0" Name="txtChange" VerticalAlignment="Top" Width="264" Text="Make a selection in this textbox" SelectionChanged="txtChange_SelectionChanged" />
<TextBox Height="87" HorizontalAlignment="Left" Margin="418,438,0,0" Name="txtStatus" VerticalAlignment="Top" Width="264" Text="Initialized text" IsReadOnly="True"/>
Now I have a selectionChanged event for one textbox defined as:
private void txtChange_SelectionChanged(object sender, RoutedEventArgs e)
{
TextBox txt2 = sender as TextBox;
txtStatus.Text = "Selection is " + txt2.SelectedText + "";
}
Could someone please explain what is going on? I have only the InitializeComponent();
in the MainWindow Constructor.
Edit: the issue gets resolved when I did not initialize Text in XAML. Any idea why?
The problem is in event SelectionChanged
which is raised in initialization. When TextBox
txtChange is initialized and Text
property is assigned the event raised and we get null reference exception in txtStatus
because it is still uninitialized. The InitializeComponent();
initializes your UI, you can find in Obj\\Debug|Release folder files MainWindow.g.cs and MainWindow.i.cs files which contains the autogenerated code of InitializeComponent();
.
If you want the second TextBox to show the text of the first, use the following XAML
<TextBlock Height="87" HorizontalAlignment="Left" Margin="418,438,0,0" Name="txtStatus" VerticalAlignment="Top" Width="264" Text="{Binding SelectedText, ElementName=txtChange}"/>
Notice that I changed your TextBox
to a TextBlock
and I am binding the Text to the SelectedText of the Textbox
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.