1

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

Hamid Pourjam
  • 20,441
  • 9
  • 58
  • 74
Vic
  • 102
  • 1
  • 2
  • 10
  • 2
    Nothing wrong, this is by design. Some properties are what is called ['ambient'](https://msdn.microsoft.com/de-de/library/system.windows.forms.ambientproperties%28v=vs.110%29.aspx) properties and are inherited from the parent of the control, ie from the container it sits in. Simply set the color to whatever you want and it will stick.. Font is another one. Very handy, when you think of it, right? – TaW Feb 17 '15 at 21:56

1 Answers1

2

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);
Hamid Pourjam
  • 20,441
  • 9
  • 58
  • 74