StackPanel doesn't support columns, it has only one column that can be stacked horizontally or vertically. Grid (which you are indeed using) supports columns and rows. Your code doesn't even refer to the Grid for adding the columns.
Your code, is almost there. Here have a look below,
sp.Children.Add(UIElement);
Whereas you need to use this code,
foreach (var child in sp.Children) {
if(child is Grid) {
}
}
Read this post to learn how to add columns and rows to Grid programmatically.
https://social.msdn.microsoft.com/Forums/vstudio/en-US/18a54950-436d-4195-84a0-e2c7835c19dd/programmatically-add-column-and-rows-to-grid-and-add-the-button-control-in-each-cell?forum=wpf[
^]
Now, when you will alter the definition of
child
, it would alter the grid that is present inside the StackPanel. Can I ask, why are you even using a StackPanel when everything has to be in a Grid. Grid is already present as a parent for this StackPanel.