维护控件之间的子/父关系

时间:2012-05-30 07:33:23

标签: c# user-interface user-controls polymorphism parent-child

我正在编写WP7 GUI并设计了一个Control类,以及一个从Control派生的ParentControl类,并且有一个子控件列表。但是,在将子项添加到ParentControl实例时,我无法访问子项的父引用,因为我将其设置为对控件的用户“保护”。

确切错误


“无法通过”控制“类型的限定符访问受保护的成员'Control.Parent';
限定符必须是'ParentControl'类型(或从中派生出来)“


    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);
        }
    }

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

是的,这是因为其他内容可能来自Control,而ParentControl只能访问其派生的控件的基本成员。例如,如果Control2派生自Control,则ParentControl不会派生自Control2,因此无法访问其基本成员。

因此,您要么使Parent成为公共属性,要么将其隐藏在远离控件的一般用户的位置,您可以通过接口进行访问,并明确地实现它:

interface IChildControl
{
    ParentControl Parent { get; set; }
}

public abstract class Control : IChildControl //such as a button or radio button
{
    ParentControl IChildControl.Parent { get; set; }
}

显式实现(IChildControl.Parent)意味着只有Control实例的消费者将看不到Parent属性。必须明确强制转换为IChildControl才能访问它。

相关问题