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

时间:2017-03-22 05:44:58

标签: c# wpf xaml nullreferenceexception

我使用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>

如果用户选择“开启”,则将启用显示特定日期的其他组合框。如果选择“自”,将显示代表strart日期和完成日期的其他组合框。 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未被用户代码处理。

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

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

1 个答案:

答案 0 :(得分:0)

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

<ComboBox x:Name="registerDateCboxReportSt" />

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

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

等...