The problem is that the order in which you create cells differs from the order in which the UniformGrid
arranges its children.
In your setCellsOnGrid
method, you create cells top-to-bottom, then left-to-right, whereas the UniformGrid
arranges its children in the order left-to-right then top-to-bottom.
For a square grid, the cells in the first column of your grid are drawn in the first row of the UniformGrid
, and similarly for other columns and rows. You end up with the grid being reflected in the line x = y. However, for a non-square grid, the length of a row does not equal the length of a column and so the grid is completely out of place.
For example, with a 3 × 3 grid, your loop runs in the following order:
1 4 7
2 5 8
3 6 9
However, the controls are added to the UniformGrid
in the following order (assuming you haven't set FlowDirection="Right"
):
1 2 3
4 5 6
7 8 9
For, for a 3 × 4 grid, your loop runs in the order
1 5 9
2 6 10
3 7 11
4 8 12
but the controls are added to the UniformGrid
in the order
1 2 3
4 5 6
7 8 9
10 11 12
This means that cells that adjacent in your cells
array might not be drawn as adjacent in the UniformGrid
, and vice versa.
Fortunately, the fix is simple: switch the order of the i
and j
loops in setCellsOnGrid
. Make the j
loop the outer loop and the i
loop the inner loop.
Incidentally, your blockSpace
method doesn't appear to use the i
and j
loop variables - it just calls the same method codeColumn * codeRow
times. Is this intentional?