Question

I want to access all elements that are inside a grid that contains columns and rows.

I made an edit on a method i found , but it always returns null .

 private static FrameworkElement GetChildren(Grid grid, int row, int column)
        {
            FrameworkElement fr = null;

            foreach (FrameworkElement child in grid.Children)
            {
                if ((Grid.GetRow(child) == row) && (Grid.GetColumn(child) == column))
                {

                      fr = child;
                }
                else
                {

                      fr = null;
                }
            }

            return fr;

        }  //getchildren
Was it helpful?

Solution

Your approach is correct but your algorithm is wrong.

Suppose that the grid contains two elements. The first one is the one you're searching for.

  1. The foreach enumerates all the controls, and returns the first one. It's the right row and column, so you assign it to fr.

  2. The foreach goes on and returns the second one. It's not the right row/column, so you assign null to fr.

  3. The foreach loop has finished enumerating the elements, and returns fr, which is null.

Basically, your code will only work if the element is the last child of the grid.

To fix your algorithm, use the break instruction to exit the loop when you find the control:

FrameworkElement fr = null;

foreach (FrameworkElement child in grid.Children)
{
    if ((Grid.GetRow(child) == row) && (Grid.GetColumn(child) == column))
    {
          fr = child;
          break;
    }
}

return fr;

Alternatively, you can use Linq to make your code shorter:

return grid.Children
    .OfType<FrameworkElement>()
    .FirstOrDefault(child => Grid.GetRow(child) == row && Grid.GetColumn(child) == column);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top