Question

I'm trying to learn and grasp what and how C# does things. I'm historically a Visual Foxpro (VFP) developer, and somewhat spoiled at the years of visual inheritance by creating my own baseline of user controls to be used application wide.

In trying to learn the parallels in C#, I am stuck on something. Say I derive my own label control (control is subclass of label) defined with a font "Arial", 10 point. Then, on any form I add it to, the Designer will automatically pre-fill in some property values which can be seen in the "Designer.cs" portion of the Form class.

this.LabelHdr2.AutoSize = true;
this.LabelHdr2.Font = new System.Drawing.Font("Arial", 14F, System.Drawing.FontStyle.Bold);
this.LabelHdr2.ForeColor = System.Drawing.Color.Blue;
this.LabelHdr2.Location = new System.Drawing.Point(150, 65);
this.LabelHdr2.Name = "LabelHdr2";
this.LabelHdr2.Size = new System.Drawing.Size(158, 22);
this.LabelHdr2.TabIndex = 5;
this.LabelHdr2.Text = "LabelHdr2";

I want to prevent things like the Font, Color, Size, AutoSize from getting generated every time a control is put on the form. If I later decide to change the font from "Arial" 10, to "Tahoma" 11, I would have to go back to all the forms (and whatever other custom controls) and edit to change over.

In VFP, if I change anything of my baseclass, all forms automatically recognize the changes. I don't have to edit anything (with exception of possible alignments via sizing impacts)... but color, font, and all else are no problems in VFP...

In C#, I have to go back and change each form so it is recognized by the new / updated values of the class...

Is there a reasonable way to avoid this?

Was it helpful?

Solution

Here is a simple solution using the ReadOnlyAttribute in the derived class.

class MyLabel : Label
{
    [ReadOnly(true)]
    public override Font Font
    {
        get { return new Font(FontFamily.GenericMonospace, 10); }
        set { /* do nothing */ }
    }
}

The ReadOnlyAttribute will disable property editing in the VS.NET designer.

OTHER TIPS

Instead of using the "ReadOnlyAttribute", try using the "DefaultValueAttribute" instead. If I remember correctly, the designer shouldn't create code to set the property if the current value matches the value stored in the "DefaultValueAttribute".

Try adding the ReadOnly attribute to the properties of your derived classes:

[ReadOnly(true)]
public override Font Font
{
    get{ // Your Implementation Here }
    set{ // Don't really care,do you? }
}

The ReadOnlyAttribute should enforce the ReadOnly behavior at design time.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top