我是在VB.NET中添加自定义控件的新手。 我想要一个类似PictureBox的控件,它具有默认的大小和图片,两者最好都是不可更改的 我首先在项目中添加了一个新类,然后添加了以下代码:
Public Class CustomControl
Inherits Windows.Forms.PictureBox
Protected Overrides Sub OnCreateControl()
MyBase.OnCreateControl()
Me.Image = Global.Mazerino.My.Resources.Resources.ControlImage
MyBase.Size = New System.Drawing.Size(20, 20) 'Also tried setting Width and Height
'properties instead.
End Sub
End Class
我执行了项目,关闭了,然后添加了控件;添加了图像,但尺寸没有改变。默认控件的大小为150,50。
所以我改为添加以下代码:
Private ControlSize As Size = New Size(10, 10)
Overloads Property Size As Size
Get
Return ControlSize
End Get
Set(value As Size)
'Nothing here...
End Set
End Property
但它也没有用,所以我试过了:
Shadows ReadOnly Property Size As Size
Get
Return ControlSize
End Get
End Property
将控件添加到表单时有效,但是当我执行程序时,我收到以下错误:"属性大小只是ReadOnly"。双击它时,它将导致表单设计中的以下代码:
Me.CustomControl1.Size = New System.Drawing.Size(10, 10)
这导致我将属性更改为读取和写入,但是当我这样做时,再一次,控件大小保持在150,50。
那么,如何将默认大小设置为特定的大小并且无法将控件添加到我的表单中?
答案 0 :(得分:0)
试试这个
Public Class CustomControl : Inherits Windows.Forms.PictureBox
Private ReadOnly INMUTABLE_SIZE As Size = New Size(20, 20)
Public Shadows Property Size As Size
Get
Return INMUTABLE_SIZE
End Get
Set(value As Size)
MyBase.Size = INMUTABLE_SIZE
End Set
End Property
Protected Overrides Sub OnSizeChanged(e As System.EventArgs)
MyBase.Size = INMUTABLE_SIZE
MyBase.OnSizeChanged(e)
End Sub
End Class
答案 1 :(得分:0)
您是否尝试过设置最小和最大尺寸?
Public Class CustomControl Inherits Windows.Forms.PictureBox
Protected Overrides Sub OnCreateControl()
MyBase.OnCreateControl()
MyBase.SizeMode = PictureBoxSizeMode.StretchImage
Me.Image = Global.Mazerino.My.Resources.Resources.ControlImage
MyBase.Size = New System.Drawing.Size(20, 20) 'Also tried setting Width and Height
'properties instead.
MyBase.MaximumSize = New Size(20,20)
MyBase.MinimumSize = New Size(20,20)
End Sub
End Class