VB.NET自定义设计器之属性编辑器自定义

属性编辑,正常来说不需要自定义,因为一般的属性,在里面都能支持,当要进行一个自定义类型的属性编辑时,就得进行属性编辑器的自定义了。
如何让自己的属性支持如在这里插入图片描述
有一个下拉框按钮呢。默认只支持内置的类型。假如想要进行自定义就是今天的内容了。
首先我们从Msdn中的得知,有一个UITypeEditor这个基类也是一个特性。
拥有它就能够进行属性的自定义了
1.建立一个自定义的class

  Public Class MyEditAttribute
     Inherits UITypeEditor
     
    End Class

然后重写四个方法,GetEditStyle、EditValue、PaintValue、GetPaintValueSupported。
接下来一一讲解

  1. GetEditStyle
    重写该方法以指定属性编辑右侧的小按钮是…还是下拉箭头。这里以下拉箭头为例也就是UITypeEditorEditStyle.DropDown
 Public Overrides Function GetEditStyle(context As System.ComponentModel.ITypeDescriptorContext) As System.Drawing.Design.UITypeEditorEditStyle

            Return UITypeEditorEditStyle.DropDown
  End Function

2.EditValue
指定了下拉箭头的风格后,接下来重写单击下拉箭头时会调用的函数。

Public Overrides Function EditValue(context As System.ComponentModel.ITypeDescriptorContext, provider As System.IServiceProvider, value As Object) As Object
   Dim edsc As IWindowsFormsEditorService = CType(provider.GetService(GetType(IWindowsFormsEditorService)), IWindowsFormsEditorService)  '声明一个下拉窗体以容纳我们接下来的控件
  '这里以列表框为例
  	Dim EditList As New Listbox
  EditList.AddRange({"FirstValue","SecondValue"})'简单的添加两个值,为字符串类型,**下面标记的属性也将是字符串类型**
  	if edsc IsNot Nothing  then
   edsc.DropDownControl(EditList) '将下拉控件设置为我们的列表框
  	End if
  '这个函数有个返回值,这个返回值即是设置属性的值。
  '这里以列表框的选项的值返回
 	 Return EditList.SelectedItem.tostring
  
 End Function

3.GetPaintValueSupported,重写这个函数的目的是让它支持属性框左侧的绘制。如Color属性在这里插入图片描述

 Public Overrides Function GetPaintValueSupported(context As System.ComponentModel.ITypeDescriptorContext) As Boolean
            Return True 'true显示左侧框框,false则为不显示
 End Function

4.PaintValue,这个即是绘制左侧框框的方法了,重写它,我们就能绘制想要的了。

  Public Overrides Sub PaintValue(e As System.Drawing.Design.PaintValueEventArgs)

            MyBase.PaintValue(e)
            e.Graphics.DrawString("test", New Font("宋体", 9), Brushes.Black, New Point(0, 0))

  End Sub

这里就绘制test文字上去吧
在这里插入图片描述
如图所示,但是你会发现超出了范围。实际上这里的左侧黑框,我们能通过e.bounds,进行获取,这样就可以在该范围内进行绘制了。具体可以自己调整,不多赘述了。
这里的所有方法重写完毕了。
最后
自定义一个控件类
声明一个TestPro属性,并在上面打上属性编辑器的标记如下

Public Class MyControl
	Inherits UserControl
	  <EditorAttribute(GetType(MyEditAttribute), GetType(System.Drawing.Design.UITypeEditor))>
	Public Property TestPro As String 
End Class

然后生成后即可看到TestPro左侧有绘制的文字右侧有个下拉箭头,单击后有一个下拉列表框。具体效果,可以自行测试。
文末:
本文这次仅以下拉框为例,当然也可以以另一种风格来编辑,但是都没多大区别,打开对话框即是以UITypeEditorEditStyle.Modal这个风格的。更多自行测试即可。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值