智能标记这个功能,可以说很少人知道,但是它是很便捷设置属性的,比如我第一篇博客中演示**鼠标交互**时就有用到这个功能。又或者文本框右上角的三角形。
本文将带领你做出这个效果。
正文
1.准备工作:导入程序集system.design,添加一个用户控件,IntelMarkCtrl引用命名空间
Imports System.Windows.Forms.Design
Imports System.ComponentModel.Design
Imports System.ComponentModel
Public Class IntelMarkCtrl
Public Property MarkCtrlText As String '声明一个文本属性
Private show_msg As Boolean
Public Property ShowMsg As Boolean '用于开启时弹框
Get
Return show_msg
End Get
Set(value As Boolean)
show_msg = value
If value Then
MsgBox("这是一个弹框")
End If
End Set
End Property
Private Sub IntelMarkCtrl_Paint(sender As Object, e As PaintEventArgs) Handles Me.Paint
e.Graphics.DrawString(MarkCtrlText, Font, New SolidBrush(ForeColor), Me.ClientRectangle) '绘制文本上去
End Sub
End Class
2.自定义一个类IntelMark继承至ControlDesigner,重写属性
ActionLists
Public Class IntelMark
Inherits ControlDesigner
'重写该属性
Public Overrides ReadOnly Property ActionLists As System.ComponentModel.Design.DesignerActionListCollection
Get
'在添加**DesignerActionList**到ActionLists时发现,有一个GetSortedActionItems()函数,这个函数里储存的是
'智能标记面板展开后的项,但是由于这是函数不是属性所以没办法直接添加项
'然而它是一个可重写的函数,所以只要继承**DesignerActionList**这个类即可
Dim DsgActCol As New DesignerActionItemCollection
Dim HeadItem As New DesignerActionHeaderItem("我是类别标题") '用于分类展示到智能面板中
Dim MkText As New DesignerActionPropertyItem("MarkCtrlText", "标记控件文本")
Dim showmsg As New DesignerActionPropertyItem("ShowMsg", "显示弹框") '第一个参数的名称必须要和MyDsgActlst里属性相同才能进行设置
DsgActCol.Add(HeadItem)
DsgActCol.Add(MkText)
DsgActCol.Add(showmsg)
Return DsgActCol
End Get
End Property
End Class
Private Class MyDsgActlst
Inherits DesignerActionList
Private mycomponet As Component '声明一个储存组件的变量
'此处创建一个函数用于属性赋值获取的便捷
Private Function GetPropertyByName(propertyname As String) As PropertyDescriptor
Dim prodes As PropertyDescriptor
prodes = TypeDescriptor.GetProperties(mycomponet)(propertyname)
If prodes Is Nothing Then
Throw New NullReferenceException("不存在该属性")
End If
Return prodes
End Function
'因为要在智能标记中设置控件属性,所以,我们要在这里声明几个属性来用于设置
Public Property MarkCtrlText As String
Get
Return GetPropertyByName("MarkCtrlText").GetValue(mycomponet)
End Get
Set(value As String)
GetPropertyByName("MarkCtrlText").SetValue(mycomponet, value)
End Set
End Property
'用于开启时弹框
Public Property ShowMsg As Boolean
Get
Return GetPropertyByName("ShowMsg").GetValue(mycomponet)
End Get
Set(value As Boolean)
GetPropertyByName("ShowMsg").SetValue(mycomponet, value)
End Set
End Property
经过以上的重写,我们终于完成了,最后又是打上设计器特性的时候了
<Designer(GetType(IntelMark))>
Public Class IntelMarkCtrl
看看最终效果
注意:智能标记有可能会出现兼容性问题,所以最好就通过属性编辑栏进行属性的设置。