I have a grid that is being populated through code. This is my implementation:
for (int i = 1; i <= 3; i++)
{
for (int j = 0; j < 3; j++)
{
Image oImage = new Image();
Window.myGrid.Children.Add(oImage);
oImageSource.UriSource = oImageUri;
oImage.Source = oImageSource;
Grid.SetRow(oImage, i);
Grid.SetColumn(oImage, j);
}
}
I’m looking for a solution that with it I will be able to do the next:
When someone clicks on the object oImage, which I added as a child, a function will trigger, and the slot’s row and column will be it’s parameters.
So if I have the next grid (each number represents an object that was appended to the grid):
1 | 2 | 3
4 | 5 | 6
7 | 8 | 9
Clicking on 9 will trigger the function func(2, 2) (row’s and column’s index is 2)
You can take advantage of the closure feature of lambda expressions to make this work, though you have to be careful.
Inside your inner
forloop, you do something like this:This will attach the specified lambda expression to the
MouseUpevent for theImageinstance, which will call your function with the appropriate values. The lambda expression will close over those variables, even after they leave scope, and it will remember their values.The key here is that you need to use locally scoped variables as the parameters. By doing so, you will create a new copy of
rowandcoleach pass through the loop. More specifically, you can not usefunc(i,j)— the lamba will “remember” the last value thatiandjhad, and will always calledfunc(3,3)on all 9 images.