2011-04-18 54 views
7

我有我用它来创建这样的元素的客户名单:Monotouch.Dialog - 哪一个元素被窃听

Foreach(Customer c in Customers) 
{ 
    //Make the StyledStringElement 
    //Set the Tapped to action a touch 
    element.Tapped +=() => { Push (new SomeController (c.ClientId)); }; 
} 

的问题是,当元素被点击它发出的最后客户SomeController()。

如何设置Tapped委托人的信息id客户

回答

13

你需要保持客户为中环路局部变量:

foreach(Customer c in Customers) 
{  
    //Make the StyledStringElement 
    //Set the Tapped to action a touch 
    var currentCustomer = c; 
    element.Tapped +=() => { Push (new SomeController (currentCustomer.ClientId)); }; 
} 

但是,这不是与MonoTouch.Dialog的限制。 Here's一篇关于一般问题的文章。

+0

这个解释非常好,现在完全有意义。 – 2011-04-19 00:36:26

+0

那篇文章太棒了。过去我曾经遇到并解决过这个问题,但Resnik的解剖非常棒。基本故障:在运行时需要执行lamda所执行的操作......此时,foreach语句中的迭代器已移至集合的末尾......所以集合中的最后一个值是什么将在拉姆达行动中使用。因此,需要局部变量将适当的值注入到lambda中。 – NovaJoe 2011-06-01 16:19:33