如何“默认”防止覆盖WinForm控件中的值? [英] How can "default" values in overridden WinForm controls be prevented?
问题描述
我正在尝试学习和掌握C#的功能以及方式。我历来是Visual Foxpro(VFP)开发人员,多年来,通过创建自己的用户控件基线以在整个应用程序范围内使用,在视觉继承的多年中有点被宠坏了。
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.
在尝试学习C#中的并行性时,我陷入了困境。假设我派生了自己的标签控件(控件是标签的子类),该控件定义了10点字体 Arial。然后,在我添加到的任何表单上,Designer都会自动预填充一些属性值,这些属性值可以在Form类的 Designer.cs部分中看到。
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";
我想防止每次控件生成诸如Font,Color,Size,AutoSize之类的东西放在表格上。如果以后我决定将字体从 Arial 10更改为 Tahoma 11,则必须返回所有表单(以及任何其他自定义控件)并进行编辑以进行更改。
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.
在VFP中,如果我更改了基类的任何内容,则所有表单都会自动识别这些更改。我不需要编辑任何内容(通过调整大小可能会导致对齐)...但是颜色,字体和其他所有内容在VFP中都没有问题...
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...
在C#中,我必须返回并更改每种形式,以便类的新值/更新值可以识别它。
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?
推荐答案
这是使用 ReadOnlyAttribute
在派生类中。
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 */ }
}
}
ReadOnlyAttribute
将在VS.NET设计器中禁用属性编辑。
The ReadOnlyAttribute
will disable property editing in the VS.NET designer.
这篇关于如何“默认”防止覆盖WinForm控件中的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!