2012-08-17 72 views
1

我目前正在开发一个应用程序到Windows Phone 7 我想获得多个rss饲料和显示在不同列表框中的每一个事件处理多个对象与参数,参数是相同的事件

我创建了一个叫做

public class RssFeed 
    { 
     public string Title { get; set; } 

     public string Url { get; set; } 

     public ListBox MyListBox { get; set; } 
    } 

我创建一个RSSFeed的名单,我尝试做以下

foreach (RssFeed item in items) 
      { 
       WebClient webClient = new WebClient(); 
       webClient.DownloadStringCompleted += new DownloadStringCompletedEventHandler((sender, e) => this.webClient_DownloadStringCompleted(sender, e, item.MyListBox)); 
       webClient.DownloadStringAsync(new System.Uri(item.Url));  
      } 

的自定义类我有事件

private void webClient_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e,ListBox listBox) 

的问题是,参数列表框是所有事件同样是当我创建的事件处理程序

例如在过去的ListBox:我有一个具有 列表项第一项具有MyListBox相等于ListBox1的 第二项具有MyListBox相等于ListBox2

事件webClient_DownloadStringCompleted将始终与参数ListBox2被称为

我该怎么做才能为参数获取不同的值。谢谢

回答

2

您正在使用一个局部变量“item”错误的方式。 由于当代码实际运行时(在foreach循环结束后很长时间)将评估Lambda表达式,因此item变量将始终指向集合中的最后一个元素。

解决方案:

foreach (RssFeed item in items) 
     { 
      var localItem = item; 
      WebClient webClient = new WebClient(); 
      webClient.DownloadStringCompleted += new DownloadStringCompletedEventHandler((sender, e) => this.webClient_DownloadStringCompleted(sender, e, localItem.MyListBox)); 
      webClient.DownloadStringAsync(new System.Uri(localItem.Url));  
     } 
1

访问修改关闭的问题。

更新您的代码:

foreach (RssFeed item in items) 
{ 
    var itemCopy = item; 
    WebClient webClient = new WebClient(); 
    webClient.DownloadStringCompleted += new DownloadStringCompletedEventHandler((sender, e) => this.webClient_DownloadStringCompleted(sender, e, itemCopy.MyListBox)); 
    webClient.DownloadStringAsync(new System.Uri(itemCopy.Url));  
} 
相关问题