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.
The
foreach
enumerates all the controls, and returns the first one. It's the right row and column, so you assign it tofr
.The
foreach
goes on and returns the second one. It's not the right row/column, so you assignnull
tofr
.The
foreach
loop has finished enumerating the elements, and returnsfr
, 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);