我是WPF的新手,每当ListBox中的选定项发生变化时,我都会尝试更新TextBlock中的文本。
我将ListBox和TextBlock添加到我的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>
但现在我不确定要添加到我的代码后面的内容。到目前为止我所拥有的是:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void VideoListBox_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
{
VideoTextBlock.Text = "Test";
}
}
然而,当我运行它时,我收到NullReferenceException错误。我想我需要以某种方式初始化TextBlock,但我不知道如何做到这一点。
答案 0 :(得分:4)
尝试使用绑定而不是事件处理程序:
<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">
<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="{Binding SelectedItem.Content, ElementName=VideoListBox}"
x:Name="VideoTextBlock"
FontSize="48"/>
</Grid>
</Window>
如果这不能满足您的需求,我会在您尝试访问之前检查null:
private void VideoListBox_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
{
if (VideoTextBlock != null)
{
VideoTextBlock.Text = "Test";
}
}