我设法得出的唯一结论是,它与 VS 为控件的第一个实例生成“designer.vb”代码以及之后不再重新生成它有关,即使基本用户控件已被更改和重新编译。
这是正确的结论。您明确告诉设计人员将BackColor
第一个控件的 设为白色,它通过将代码插入将属性*.Designer.vb
设置为白色的文件来遵守。BackColor
它无条件地执行此操作,以便它覆盖控件的默认 BackColor
属性。
当您BackColor
将控件的默认属性更改为红色时,这会影响已创建的控件的所有新实例,因为它们仍在使用默认属性值。但它不会影响您已明确覆盖该属性值的控件实例。
尽管这种行为在您看来并不直观,但它实际上是设计使然。如果您希望控件的所有实例都继承默认背景颜色,则不要BackColor
为它的单个实例设置属性。
要强制控件的特定实例使用默认背景颜色,即使您已明确设置它,右键单击属性窗口中的属性并选择“重置”。在这种情况下,自定义控件的第一个实例的背景应变为红色,因为它继承了该特定属性的默认值。
为了响应您的更新,问题在于各种控件类设置了它们自己的默认值(通过它们自己从它们的父类覆盖它们Control
)。如果您想用自定义控件的新默认值覆盖那些,您需要为此在自定义控件类中编写代码。您不能在设计器中执行此操作,因为这只影响自定义控件的特定实例,而不影响整个类。
您需要特别做两件事。首先,覆盖相关属性并使用DefaultValueAttribute
. 其次,在类的构造函数中设置属性的默认值。
下面是一个继承自默认控件的自定义控件的示例Label
。我有所有标准控件的版本,基本上只是默认强制FlatStyle
属性FlatStyle.System
。该代码在 VB.NET 中是任意的,但如果 C# 是您的首选方言,您应该能够轻松转换它。
Imports System.Windows.Forms
Imports System.ComponentModel
Imports System.Drawing
<ToolboxItem(True)> <ToolboxBitmap(GetType(ResFinder), "LabelEx.bmp")> _
<Description("A standard Windows label control for displaying static text and images.")> _
Public Class LabelEx : Inherits Label
''' <summary>
''' Gets or sets the flat style appearance of this label control.
''' </summary>
<DefaultValue(GetType(System.Windows.Forms.FlatStyle), "System")> _
Public Shadows Property FlatStyle As FlatStyle
'Set the default flat style to System
Get
Return MyBase.FlatStyle
End Get
Set(ByVal value As FlatStyle)
MyBase.FlatStyle = value
End Set
End Property
''' <summary>
''' Initializes a new instance of the LabelEx" class with default settings.
''' </summary>
Public Sub New()
MyBase.New()
'Set default property values
Me.FlatStyle = FlatStyle.System
End Sub
End Class
此一般规则的唯一主要例外是如果您想更改控件的大小或填充的默认值。在这种情况下,您应该只覆盖 protectedDefaultSize
和DefaultPadding
属性;IE
''' <summary>
''' Gets the default Size of a ButtonEx control.
''' </summary>
Protected Overrides ReadOnly Property DefaultSize As Size
Get
Return New Size(88, 26)
End Get
End Property
''' <summary>
''' Gets the spacing, in pixels, around the image that is displayed on this button control.
''' </summary>
Protected Overrides ReadOnly Property DefaultPadding As Padding
Get
Return New Padding(7, 0, 0, 0)
End Get
End Property
在这种情况下,您不应在构造函数中为公共属性设置默认值。
有关如何编写自定义控件(以及一些有用的控件!)的更多线索,您可以查看Windows Forms Aero库。