I'm really new to WPF and I'm trying to update the text in a TextBlock whenever the selected item in a ListBox changes.
I added the ListBox and TextBlock to my XAML:
<Window x:Class="Blend_Test.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" WindowState="Maximized" ResizeMode="NoResize" Width="{DynamicResource {x:Static SystemParameters.PrimaryScreenWidthKey}}" Height="{DynamicResource {x:Static SystemParameters.PrimaryScreenHeightKey}}">
<Grid Background="#FFC10000">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<ListBox Grid.Column="0" Margin="20" FontSize="48" Name="VideoListBox" SelectedIndex="0" Cursor="None" SelectionChanged="VideoListBox_SelectionChanged">
<ListBoxItem Margin="20">Video 1</ListBoxItem>
<ListBoxItem Margin="20">Video 2</ListBoxItem>
<ListBoxItem Margin="20">Video 3</ListBoxItem>
<ListBoxItem Margin="20">Video 4</ListBoxItem>
</ListBox>
<TextBlock Grid.Column="1" Text="Lorem Ipsum" x:Name="VideoTextBlock" FontSize="48"></TextBlock>
</Grid>
</Window>
But now I'm not exactly sure what to add to my code behind. What I have so far is:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void VideoListBox_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
{
VideoTextBlock.Text = "Test";
}
}
However when I run this I'm getting a NullReferenceException error. I think I need to initialize the TextBlock somehow, but I'm not sure how to do this.
VideoTextBlock.Text = "Test";? - PoweredByOrangeListBoxis being created before theTextBlockin your XAML, and once aListBoxis created, theSelectionChangedevent is triggered - notice that at this point theTextBlockis still NOT created, so you get aNulReferenceException. Not sure what your design is, but you can check to see if theTextBlockis null or not before changing its text. Once the window is shown, you'll notice that changing the selected item will actually update theTextBlock. - PoweredByOrange