2013-05-04 119 views
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(); 
    } 
    } 
} 
+0

我编辑了你的标题。请参阅:“[应该在其标题中包含”标签“](http://meta.stackexchange.com/questions/19190/)”,其中的共识是“不,他们不应该”。 – 2013-05-04 20:31:19

+0

发生这种情况时,Visual Studio的输出窗口中有什么? – 2014-01-22 08:27:48

回答

0

你已经设置的ItemsSource接受一种类型的物品,但你要添加一个字符串到它。在添加它之前将字符串转换为Item,以便它与ItemSource的预期类型匹配。

0

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

相关问题