views:

46

answers:

1

I've got a really weird problem and i'm wondering if it's a visual's bug or if i'm doing something wrong. Here's a simple code of an overriden Panel class:

public class MyPanel : Panel
    {
        private TableLayoutPanel table = new TableLayoutPanel();

        public MyPanel()
        {
            this.Controls.Add(table);
            table.BackColor = Color.Green;
        }

        public override System.Drawing.Color BackColor
        {
            get
            {
                return table.BackColor;
            }
            set
            {
                table.BackColor = value;
            }
        }
    }

If i put the control on a form and build the project, visual will generate an error and opening the project again will be impossible. However if i change TableLayoutPanel to TextBox, it works fine. Also, if i set the BackColor in the constructor before adding the control to the Controls collection, it also works fine. What is the problem? or is it just a bug?

A: 

I suspect recursion may be an issue; by default (if not set explicitly) a control inherits color from the parent. This leads to the scenario where the child's color (if not set) asks the parent, which asks the child (forever).

TextBox, however, overrides this behaviour to return SystemColors.Window if there isn't an explicit color set. Hence no recursion.

Either way, I'm not sure this is a good idea - the designer might start duplicating controls if you aren't careful.

Marc Gravell
then why would it work with TextBox?
agnieszka
and i must add that i checked that the property BackColor's get is used after finishing MyPanel's constructor
agnieszka
actually you were right. thanks! i spent a long time with this problem
agnieszka
Did you try table.BackColor? And note that all bets on behavior are "off" until you actually generate real (Win32) controls (i.e. it is added to a form).
Marc Gravell