如何解决在子窗口VB.NET 2015中访问MDI父状态条
VB.NET 2015-在MDI窗口中将带有2个ToolStripStatusLabel的StatusStrip控件放置在其上。当我打开一个新表单时,这将是MDI窗口的子窗口。
如何从信息ToolStripStatusLabel中读取信息。
For Each不会循环遍历StatusStrip中的所有项,据我了解,ToolStripStatusLabel并不是这样的控件,因此For Each循环不起作用。
由于与上述相同的原因,Me.Owner.Controls也无法访问ToolStripStatusLabel
该怎么办?
解决方法
任何子窗体从其父窗体获取数据的正确方法是让子窗体引发一个事件,并使父窗体通过事件args将数据传递回子窗体。这样,孩子就不必知道有关父表单的任何特定信息,因此,从理论上讲,许多不同的父表单可以显示相同的子表单并传递数据。这是一个松耦合的例子。
子窗体看起来像这样,提供一个事件,该事件在需要数据时引发,并通过创建的自定义EventArgs
对象获取数据:
Public Class Form2
Public Event StatusDataNeeded As EventHandler(Of StatusDataNeededEventArgs)
Protected Overridable Sub OnStatusDataNeeded(e As StatusDataNeededEventArgs)
RaiseEvent StatusDataNeeded(Me,e)
End Sub
Private Sub GetStatusData()
Dim e As New StatusDataNeededEventArgs
OnStatusDataNeeded(e)
MessageBox.Show(e.StatusData)
End Sub
'...
End Class
Public Class StatusDataNeededEventArgs
Public Property StatusData As String
End Class
如您所见,那里不依赖于任何特定类型的父表单,也不依赖于该表单是MDI子级。它只是引发事件,任何人都可以提供状态数据,无论它们之间的关系如何。
在您的情况下,MDI父表单可能看起来像这样:
Public Class Form1
'Stores the data that will be displayed in the StatusStrip.
Private statusData As String
'Display the status data in the StatusStrip.
Private Sub SetStatusText()
ToolStripStatusLabel1.Text = statusData
End Sub
'Create and display a child form.
Private Sub DisplayChildForm()
Dim childForm As New Form2 With {.MdiParent = Me}
'Handle the event raised when the child requires the status data.
AddHandler childForm.StatusDataNeeded,AddressOf ChildForm_StatusDataNeeded
childForm.Show()
End Sub
'Pass the status data to the child form.
Private Sub ChildForm_StatusDataNeeded(sender As Object,e As StatusDataNeededEventArgs)
e.StatusData = statusData
End Sub
'...
End Class
如您所见,状态数据存储在其自己的字段中。 StatusStrip
用于显示状态数据,而不用于存储。父表单创建并显示子表单并处理事件。在事件处理程序中,它只是将状态数据传递到e
参数的属性。
要了解有关创建自己的事件的更多信息,请参见here。
, jmcilhinney的事件方法绝对是一种更好的方法,但是作为一种快速解决方案,My
命名空间可以在VB.Net中使用。
My.Forms.<Form Name>.<Control name>.<property>
例如:
My.Forms.AM_MDI.ToolStripStatusLabel1.Text
对于那些希望在“我的命名空间”上阅读更多内容的人- VB.NET中的命名空间 https://www.thoughtco.com/namespaces-in-vbnet-3424445
您是否在VB.NET中使用“我的”命名空间? Do you use the 'My' namespace in VB.NET?
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。