0

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

这就是我到目前为止所拥有的。导致它关闭的行是: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();
    }
  }
}
4

2 回答 2

0

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

于 2013-05-04T20:36:34.203 回答
0

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

于 2013-05-04T20:39:00.293 回答