I am using a class that contains some properties and 2 UserControls that I created; they represent 2 different parts of the UI. I structured the class this way to make sure that every time an object of the class changes, the UI is updated in two parts.
The controls are placed inside different grids, and their position in the grid depends from the position of the class in a list.
To avoid waste of resources, I create the instance of the UserControl only when I need it (I need the graphical part of the class only when it is added to the list, otherwise the properties are enough).
This way sometimes I get an error because the software tries to modifies a UserControl that has not been instantiated, resulting in an exception.
This is an example of the code that breaks:
for (int i = 0; i < ListRouter.LRouter.Count(); i++)
{
ListRouter.LRouter[i].Knob.SetPosition(i);
ListRouter.LRouter[i].SensorMenu.SetPosition(i);
}
What check should I do before trying to pass the index to the UserControl?
The same when I try to set row and column of the UserControl, but it has not been added to the Grid yet. I tried to solve this problem with this check:
if (LogicalTreeHelper.GetParent(r.Knob) != null)
{
Grid.SetRow(r.Knob, r.Knob.GridRow);
Grid.SetColumn(r.Knob, r.Knob.GridColumn);
}
Will this be enough? Are there better solutions? Thanks