Windows Phone using Grid
I have a grid with 7 rows and 7 columns. I want to dynamically insert a control into each cell.
To add controls i use this code
Rectangle newRectangle = new Rectangle();
newRectangle.Tap += new EventHandler<GestureEventArgs>(Rectangle_KeyDown);
newRectangle.Fill = HighlightColor;
Grid.SetColumn(newRectangle, i);
Grid.SetRow(newRectangle, ii);
grid1.Children.Add(newRectangle);
How can I get one of these controls out of position x,y
?
I thought something like
Grid.GetColumn( ?? );
Grid.GetRow( ?? );
But I don't know how to proceed.
I really hope someone can help me.
There is no built-in function for this, so you must search manually. But you can easily write a search function like this with Linq for example:
var rectangleAtXy = grid.Children.OfType<Rectangle>()
.SingleOrDefault(c => Grid.GetColumn(c) == x && Grid.GetRow(c) == y);
There is no function for this. You have to read the attached Row
amd properties Column
of the grid children to determine which cell they are in.
I'm not sure what you are trying to do there, but I could suggest a different, cleaner approach that might work for you.
It includes the use of a ListBox with a UniformGrid as the ItemsPanelTemplate. Then you will create a collection and set it as the ItemsSource for this list. You can now populate your list with your controls using a simple conversion from a 2D perspective (col, row) to a single dimensional list (your list). Setting up and retrieving controls is now as easy as this transformation.