NullReferenceException

NullReferenceException

这个问题已经有了答案:
What is a NullReferenceException, and how do I fix it?
31答
我的代码在对checkbox2的调用中遇到了nullreferenceexception。异常表示StackPanelListBox为空。它在xaml中声明,同样声明的stackpanel不为空。这里怎么了?
这是xaml:

<Window x:Class="ch0103.WPF.LayoutWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="LayoutWindow" Height="450" Width="900">
    <StackPanel Name="stackPanelMain">
        <WrapPanel>
            <CheckBox Name="checkBox1" VerticalAlignment="Center" IsThreeState="False"     IsChecked="True" Click="checkBox_Checked" Content="Button StackPanel" Margin="0,0,11,0" />
            <CheckBox Content="Listbox StackPanel" Height="16" Name="checkBox2" IsChecked="True" Checked="checkBox2_Checked" />
        </WrapPanel>
        <Grid Name="grid1" ShowGridLines="True">
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="Auto" />
                <ColumnDefinition />
                <ColumnDefinition />
            </Grid.ColumnDefinitions>
            <StackPanel HorizontalAlignment="Left" Name="stackPanelButtons" VerticalAlignment="Top" Visibility="Visible">
                <Button Content="Button" Height="23" Name="button1" />
                <Button Content="Button" Height="23" Name="button2" />
                <Button Content="Button" Height="23" Name="button3" />
            </StackPanel>
            <StackPanel Name="stackPanelListbox" Grid.Column="1">
                <ListBox Grid.Column="2" HorizontalAlignment="Left" Name="listBox1" VerticalAlignment="Top" Width="200">
                    <ListBoxItem Content="Test" />
                    <ListBoxItem Content="Test" />
                    <ListBoxItem Content="Test" />
                    <ListBoxItem Content="Test" />
                    <ListBoxItem Content="Test" />
                    <ListBoxItem Content="Test" />
                    <ListBoxItem Content="Test" />
                </ListBox>
            </StackPanel>
        </Grid>
    </StackPanel>
</Window>

这是C代码:
using System.Windows;

namespace ch0103.WPF
{
    /// <summary>
    /// Interaction logic for LayoutWindow.xaml
    /// </summary>
    public partial class LayoutWindow : Window
    {
        public LayoutWindow() {
            InitializeComponent();
        }

        private void checkBox_Checked(object sender, RoutedEventArgs e) {
            stackPanelButtons.Visibility = (bool) checkBox1.IsChecked ?
                Visibility.Visible : Visibility.Collapsed;
        }

        private void checkBox2_Checked(object sender, RoutedEventArgs e) {
            stackPanelListbox.Visibility = (bool) checkBox2.IsChecked ? // stackPanelListbox is null here?
                Visibility.Visible : Visibility.Collapsed;
        }
    }
}

最佳答案

何时引发异常?在窗口启动时,或在按下复选框后?
如果它在启动时处于,可能是因为checkbox2_checked()在initializecompents()期间调用,而stackpanellistbox尚未声明。

10-08 07:50
查看更多