Search code examples
winformsbackcolor

How can I prevent that the BackColor of a control is changed?


I want a panel inheriting from a base panel to have a fixed BackColor no matter where it is used. My base panel looks like this:

public class MyPanel
{
    public override Color BackColor
    {
        get
        {
            return base.BackColor;
        }
        set
        {
            base.BackColor = Color.Red;
        }
    }
}

The BackColor is not set in the Designer.cs file of an example form:

this.sampleControl.Font = new System.Drawing.Font("Tahoma", 8.25F,
    System.Drawing.FontStyle.Regular, 
    System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.sampleControl.Location = new System.Drawing.Point(0, 0);
this.sampleControl.Margin = new System.Windows.Forms.Padding(5);
this.sampleControl.Name = "sampleControl";
this.sampleControl.Padding = new System.Windows.Forms.Padding(2, 0, 2, 2);
this.sampleControl.Size = new System.Drawing.Size(230, 100);
this.sampleControl.TabIndex = 1;

In fact there is no color set anywhere, so I suppose it somehow gets the property from the panel it is placed in. How can I prevent this?


Solution

  • How about:

    public class MyPanel : Panel
    {
        private Color backColor = Color.Red;
    
        public MyPanel()
        {
            // Set the color once
            this.BackColor = backColor;
        }
    
        public override Color BackColor
        {
            get
            {
                return base.BackColor;
            }
            set
            {
                base.BackColor = backColor;
            }
        }
    }