Search code examples
c#.netwinformspanelbackcolor

Panel BackColor setting color of it's controls


I want to set the background color of the panel area only but it somehow also sets the background color of its controls, what's wrong with it?

public Form1()
    {
        InitializeComponent();
        Panel p = new Panel();
        p.Size = this.ClientSize;
        p.BackColor = Color.Black; // The button will also have black background color
        Button b = new Button();
        b.Size = new Size(this.ClientSize.Width, 50);
        p.Controls.Add(b);
        this.Controls.Add(p);
    }

see the result here


Solution

  • This is by design. The BackColor property is an ambient property by default, meaning that it inherits its value from its parent control. When you set it explicitly to a particular value, that overrides the ambient nature and forces it to use that particular value.

    explicitly set the color of button like this

    p.Controls.Add(b);
    b.BackColor = Color.White;
    this.Controls.Add(p);