将项目添加到列表框时应用程序崩溃

时间:2013-05-04 20:29:37

标签: c# windows-phone

当我尝试向列表框添加任何内容时,应用程序将关闭。

这是我到目前为止所拥有的。导致它关闭的行是:listBox1.Items.Add(term1)

using System;
using System.IO;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls; 
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;

namespace PhoneApp1 {
    public partial class MainPage : PhoneApplicationPage {
    // Constructor
    public class Item {
        public string itemLine1 { get; set; }
        public string itemLine2 { get; set; }
    }

    public MainPage() {
        InitializeComponent();
        List<Item> list = new List<Item>();
        Item item = new Item();
        item.itemLine1 = "Item11";
        item.itemLine2 = "Item12";
        list.Add(item);
        item = new Item();
        item.itemLine1 = "Item21";
        item.itemLine2 = "Item22";
        list.Add(item);
        item = new Item();
        item.itemLine1 = "Item31";
        item.itemLine2 = "Item32";
        list.Add(item);

        Dispatcher.BeginInvoke(new Action(() =>
        listBox1.ItemsSource = list
        ));

        WebClient wc = new WebClient();
        wc.DownloadStringCompleted += new DownloadStringCompletedEventHandler (wc_DownloadStringCompleted);
        wc.DownloadStringAsync(new Uri("http://www.usi.edu/webservices/iphone/USIINFOterms.xml"));

    }

    void wc_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e) {
        ApplicationTitle.Text = e.Result;            
        string terms = ApplicationTitle.Text;
        ApplicationTitle.Text = "Course Catalog";
        string term1 = terms.Substring(terms.IndexOf("value"+7),terms.IndexOf("/value"));
        listBox1.Items.Add(term1);
    }

    private void ListBox1_SelectionChanged(object sender, SelectionChangedEventArgs e) {
        if (sender != null) PageTitle.Text = sender.ToString();
        if (e != null) PageTitle.Text = e.AddedItems.Count.ToString();

        IEnumerator ie = e.AddedItems.GetEnumerator();
        ie.MoveNext();

        if (e != null) ApplicationTitle.Text = ie.Current.ToString();
    }
  }
}

2 个答案:

答案 0 :(得分:0)

您已将ItemsSource设置为接受一种Item类型,但随后您将向其中添加一个字符串。在添加之前将字符串转换为Item,以便它匹配ItemSource的预期类型。

答案 1 :(得分:0)

您正在尝试将字符串添加到项目列表中。我的猜测是你得到一个InvalidTypeException或类似的东西。而不是listBox1.Items.Add(term1),请尝试创建新项目并将term1分配给item.itemLine1,然后listBox1.Items.Add(item)