WPF 错误对象引用未设置到对象的实例

WPF error Object reference not set to an instance of an object

我使用 WPF 并在 Xaml 中有一个组合框:

<ComboBox Name="registerDateCboxReportSt"  SelectedIndex="0"
                            Height="30"  Width="91.478" 
                            HorizontalAlignment="Left" 
                            VerticalAlignment="Center"
                            Margin="99.323,3,0,3"
                            SelectionChanged="registerDateCboxReportSt_SelectionChanged" >
                            <ComboBoxItem Content="select Date:" Padding="5" />
                            <ComboBoxItem Content="On" Padding="5" />
                            <ComboBoxItem Content="Since" Padding="5" />
                        </ComboBox>

如果用户 select "On" 将启用显示特定日期的其他组合框。如果 selects "Since" 将显示代表开始日期和完成日期的其他组合框。 C# 代码是:

    private void registerDateCboxReportSt_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        switch (registerDateCboxReportSt.SelectedIndex) 
        {
            case 0 :
                startDayReportSt.IsEnabled = startMonthReportSt.IsEnabled = startYearReportSt.IsEnabled = false;
                finishDayReportSt.IsEnabled = finishMonthReportSt.IsEnabled = finishYearReportSt.IsEnabled = false;
                break;
            case 1:
                startDayReportSt.IsEnabled = startMonthReportSt.IsEnabled = startYearReportSt.IsEnabled = true;
                finishDayReportSt.IsEnabled = finishMonthReportSt.IsEnabled = finishYearReportSt.IsEnabled = false;
                break;
            case 2:
                 startDayReportSt.IsEnabled = startMonthReportSt.IsEnabled = startYearReportSt.IsEnabled = true;
                finishDayReportSt.IsEnabled = finishMonthReportSt.IsEnabled = finishYearReportSt.IsEnabled = true;
                break;
        }
    }

当我开始 运行 应用程序时, "case 0:" 之后的行导致错误! 这一行:

startDayReportSt.IsEnabled = startMonthReportSt.IsEnabled = startYearReportSt.IsEnabled = false;

导致错误! 错误代码是:

用户代码未处理 nullreferenceexception。

对象引用未设置为对象的实例。

为什么这一行会导致错误?!

尝试在 xaml 中使用 x:Name=".." 而不是 Name=".."

<ComboBox x:Name="registerDateCboxReportSt" />

对代码隐藏中需要访问的所有元素执行此操作。

x:Name="startDayReportSt" x:Name="startMonthReportSt" x:Name="startYearReportSt"

等...