0

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

Flat Eric
  • 7,827
  • 9
  • 34
  • 44
Hamma
  • 173
  • 1
  • 2
  • 12
  • Why cant you use if (object != null){} – Syed Farjad Zia Zaidi May 29 '14 at 08:35
  • I expanded on an [All controls method](http://stackoverflow.com/questions/17454389/generic-all-controls-method) that you could use to get all instances of a control on a form, and then just check if this list contains any of the control you are looking for – Sayse May 29 '14 at 08:39
  • I was looking for a solution like if (object != null){}. Honestly I also though about that, but I wasn't sure it would fix my problem entirely. And about the grid? – Hamma May 29 '14 at 08:43

0 Answers0