Monotouch.Dialog - Which Element was Tapped
Asked Answered
R

1

7

I have a list of Customers which I use to create Elements like this:

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

The problem is that when the element is tapped it sends the last customer to SomeController().

How can I set the Tapped Delegate with information that will id the customer?

Renal answered 18/4, 2011 at 8:39 Comment(0)
D
13

You need to keep the customer as local variable in the loop:

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)); };
}

But this is not a limitation with MonoTouch.Dialog. Here's an article about the general problem.

Deloresdeloria answered 18/4, 2011 at 9:38 Comment(1)
That article is fantastic. I've encountered and resolved this problem on my own in the past, but Resnik's dissection is awesome. Basic breakdown: the action that the lamda performs is created as soon as it's needed at runtime...at that point the iterator in the foreach statement has already been moved to the end of the collection...so the last value in the collection is what will be used in the lamda action. Hence, the need for the local variable to inject the proper value into the lambda.Hardan

© 2022 - 2024 — McMap. All rights reserved.