I’m coding a WP7 GUI and have designed a Control class, and a ParentControl class that derives from Control and has a list of child controls. However, when adding a child to a ParentControl instance, I’m unable to access the child’s parent reference because I set it to be ‘protected’ from users of the controls.
The exact error is
“Cannot access protected member ‘Control.Parent’ via a qualifier of type ‘Control’;
the qualifier must be of type ‘ParentControl’ (or derived from it)”
public abstract class Control //such as a button or radio button
{
public ParentControl Parent { get; protected set; }
}
public abstract class ParentControl : Control //such as a panel or menu
{
protected List<Control> children = new List<Control>();;
public void AddChild(Control child, int index)
{
NeedSizeUpdate = true;
if (child.Parent != null)
child.Parent.RemoveChild(child);
child.Parent = this; //How do I access the parent?
children.Insert(index, child);
OnChildAdded(index, child);
}
}
How might I fix this?
Yes, this is because other things may derive from
Control, andParentControlcan only access base members of controls it derives from. For instance, ifControl2derived fromControl, thenParentControlwould not derive fromControl2and so could not access it’s base members.So, you either make
Parenta public property, or if you want to keep it hidden away from general users of the control, you could make access via an interface, and implement it explicitly:The explicit implementation (
IChildControl.Parent) means that consumers with just aControlinstance will not see theParentproperty. It must be explicitly cast toIChildControlto access it.