How to create a custom control property as form, and the property have options of all forms from the Project?
我正在使用 VB.Net 开发一个 winform 项目。在这个项目中,我创建了一个继承自 UserControl 的自定义按钮,并添加了一个 FormName 属性作为 Form。这样我就可以将 FormName 属性分配给单击自定义按钮时程序将打开的表单。该属性实际上显示在 Visual Studio 属性面板中,但仅显示表单本身作为唯一选项,我们不能从同一项目中选择其他表单。
这是该属性的代码
1
2 3 4 5 6 7 8 |
<Browsable(True), Description("Set the Form Name")> Public Property FormName As Form
Get Return _formName End Get Set(ByVal value As Form) _formName = value End Set End Property |
我尝试将上述属性更改为字符串并以字符串格式输入表单名称。之后,我创建了一个 openForm 函数来通过接收字符串作为参数来打开表单,因此基本上获取字符串表单名称并创建一个新的表单实例。但最后,我在与表单的控件(如文本框)交互时遇到问题,因为表单有两个实例。所以我放弃了这个想法。
这是我从字符串名称打开表单的 openForm 函数代码:
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
Public Function openForm(ByVal frm As String, Optional ByVal focusCtrl As Control = Nothing, Optional ByVal isFullscreen As Boolean = True, Optional ByVal isDialog As Boolean = False) As Form
Dim obj As Form = TryCast(Activator.CreateInstance(Type.GetType("Management_System." + frm)), Form) Dim myAnimator As New FormAnimator(obj, FormAnimator.AnimationTypes.Blend, fadingTime) obj.StartPosition = FormStartPosition.CenterScreen If isDialog Then obj.ShowDialog() focusCtrl.Focus() Else Dim frms = Application.OpenForms Dim isOpened As Boolean = False For Each q In frms If q.GetType().Name = obj.Name Then obj = CType(q, Form) isOpened = True Exit For Else isOpened = False End If Next If isOpened = True Then If isFullscreen Then obj.WindowState = FormWindowState.Maximized Else obj.WindowState = FormWindowState.Normal End If If obj.Visible Then obj.BringToFront() Else obj.Show() End If Else obj.Show() obj.BringToFront() End If End If Return obj End Function |
预期的输出是作为表单的自定义控件属性,它具有项目中所有表单的选项。
请帮助解决这个问题。提前感谢
编辑:
1
2 3 4 5 6 7 8 9 |
Private Sub Button_Click(sender As Object, e As EventArgs) Handles cbtnPurchase.Click, cbtnPurchaseReturn.Click, cbtnSales.Click, cbtnSalesReturn.Click, cbtnMutationIn.Click, cbtnMutationOut.Click, cbtnSwitchWarehouse.Click, cbtnOpname.Click, cbtnCakery.Click
Try Dim btn As customButton = CType(sender, customButton) If ExitForm Then Return openForm(btn.FormName) Catch ex As Exception MsgTryCatch(ex.Message) End Try End Sub |
假设一个字符串属性对你来说已经足够好了,在 VB.NET 项目中,你可以依赖
1
2 3 4 5 6 7 8 9 10 11 12 13 14 |
Public Class MyButton
Inherits Button Public Property Form As String Protected Overrides Sub OnClick(e As EventArgs) If (Not String.IsNullOrEmpty(Form)) Then Dim fp = My.Forms.GetType().GetProperty(Form) If (fp IsNot Nothing) Then Dim f = fp.GetValue(My.Forms) DirectCast(f, Form).ShowDialog() End If End If MyBase.OnClick(e) End Sub End Class |
如果您有兴趣获得更好的设计时支持,请查看这篇文章:
- 如何创建一个显示所有可用表单列表的 UserControl 属性?
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/269563.html