C# 为什么我的windows phone应用程序在单击按钮时崩溃?

C# 为什么我的windows phone应用程序在单击按钮时崩溃?,c#,C#,我正在visual Studio 2010中为windows phone 7制作一个宠物商店应用程序。我正在尝试从一个页面获取已复制到app.xaml中临时列表的项目(可以在调试器中看到),以显示在篮框页面的其他列表中,但当单击指向篮框页面的按钮时,应用程序崩溃。我没有对应用程序的任何部分使用绑定 private void btnAdd_Click(object sender, RoutedEventArgs e) { thisApp.petBasket.Add(lst

我正在visual Studio 2010中为windows phone 7制作一个宠物商店应用程序。我正在尝试从一个页面获取已复制到app.xaml中临时列表的项目(可以在调试器中看到),以显示在篮框页面的其他列表中,但当单击指向篮框页面的按钮时,应用程序崩溃。我没有对应用程序的任何部分使用绑定

 private void btnAdd_Click(object sender, RoutedEventArgs e)
    {
        thisApp.petBasket.Add(lstAllPets.SelectedItem as Pets);
        MessageBox.Show("Item added to the Basket");
    }
这是用于将项目添加到临时列表的代码

    public void ShowBasket()
    {
        if (thisApp.petBasket != null)
        {
            //show pets that have been added to the basket
            foreach (Pets currpet in thisApp.petBasket)
            {
                lstBasketItems.Items.Add(currpet.Name + "" + currpet.Gender + "" + currpet.Dob + "" + currpet.Category + "");
            }
        }
    }
这是我用来尝试输出项目的代码,但它会使应用程序崩溃


有人知道问题出在哪里吗?

您的应用程序可能会崩溃,因为您的宠物篮包含空值

thisApp.petBasket.Add(lstAllPets.SelectedItem as Pets);
如果所选项目不是
Pets
,则
操作符as
返回null,并将其放入列表中。稍后,您只需迭代而不检查空值

foreach (Pets currpet in thisApp.petBasket)
{
    lstBasketItems.Items.Add(currpet.Name + "" + currpet.Gender + "" + currpet.Dob + "" + currpet.Category + "");
}
您应该选中所选项目

var pet = lstAllPets.SelectedItem as Pets;
if(pet != null)
    thisApp.petBasket.Add(pet);

您也可以在
foreach
循环中检查
currpet

在您将项目添加到购物篮并返回主页后,当您单击按钮进入购物篮页面时,当应用程序崩溃时,运行代码时,我没有收到错误消息。我们发现使其崩溃的代码行位于foreach循环中,以在注释掉该项目时显示该项目。应用程序不会崩溃,但当您将该代码行放回时,这是崩溃发生时,但我不知道如何修复它