用户c#未处理Nullreferenceexception

时间:2013-12-08 19:13:20

标签: c# windows-phone-8 nullreferenceexception

我正在学习为WP8编写c#。

错误是:“对象引用未设置为对象的实例。”

我收到此错误并且不知道为什么,我在其他类中使用了类似的代码并且它工作正常/ =

如果您需要更多信息请告诉我,谢谢!(=

 public partial class DisplayScenario : PhoneApplicationPage
{
    public event PropertyChangedEventHandler PropertyChanged;
    protected void NotifyPropertyChanged(string propertyName)
    {
        PropertyChangedEventHandler temp = PropertyChanged;
        if (temp != null)
        {
            temp(this, new PropertyChangedEventArgs(propertyName));
        }
    }

    int index;
    private MyDataContext database;
    private ObservableCollection<Questions> questionList;
    public ObservableCollection<Questions> QuestionList
    {
        get
        {
            return questionList;
        }
        set
        {
            if (questionList != value)
            {
                questionList = value;
                NotifyPropertyChanged("QuestionList");
            }
        }
    }

    public void DisplaySceanrio()
    {
        InitializeComponent();
        this.DataContext = this;
    }

    protected override void OnNavigatedTo(NavigationEventArgs e)
    {
        base.OnNavigatedTo(e);
      //  QuestionsList.ItemsSource = null;

        if (NavigationContext.QueryString.ContainsKey("index"))
        {
            string value;

            NavigationContext.QueryString.TryGetValue("index", out value);
            index = System.Convert.ToInt32(value);

        } 
        database = new MyDataContext();

        QuestionList = new ObservableCollection<Questions>(from Questions q in database.MyQuestions where q.Id == index select q);
        //Getting error here: vvv
        QuestionsList.ItemsSource = QuestionList;

    }

这是listBox的xaml:

<ListBox x:Name="QuestionsList" ItemsSource="{Binding QuestionList}" SelectionChanged="QuestionTapped" >
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <TextBlock x:Name="QuestionName" Text="{Binding Question, Mode=OneWay}"/>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>

1 个答案:

答案 0 :(得分:3)

调用OnNavigatedTo方法时尚未创建QuestionsList。它在XAML中定义。

如果您使用了Loaded事件处理程序,那么您知道ListBox已经创建并且您可以引用它:

public DisplayScenario()
{
    InitializeComponent();
    this.Loaded += DisplayScenario_Loaded;
}

void DisplayScenario_Loaded(object sender, RoutedEventArgs e)
{
    QuestionsList.ItemsSource = QuestionList;
}

此外,您的构造函数有一个拼写错误,永远不会被调用。它应该是DisplayScenario()。

public DisplayScenario()
{
    InitializeComponent();
    this.DataContext = this;
}