我知道有很多关于这个问题的帖子,但我无法解决这个问题。
我正在开发一个基于 vb.NET Form 的应用程序。我正在尝试将控件添加到 Tabcontrol。要添加到 tabcontrol 的控件位于不同的项目中。Tabcontrol 是第三方(Infragistics)控件,与 .NET Tabcontrol 相同,但具有一些额外功能。下面是我将控件添加到 Tabcontrol 的代码行。
fViewerForm.DocumentViewer1.ThumbnailPane.TabControl.Tabs(tnp_PageTab_ID).TabPage.Controls.Add(fViewerForm.DocumentViewer1.ThumbnailPane.TNViewer1.TNImage(0))
Control TnImage(0)是一个 userControl 并且在一些不同的项目中。我收到以下错误: “在一个线程上创建的控件不能作为另一个线程上的控件的父级。”
在浏览了几篇帖子后,我发现可以使用Invoke方法来解决此类问题。所以我修改了我的代码:
fViewerForm.DocumentViewer1.ThumbnailPane.AddControlToTabControl(tnp_PageTab_ID, fViewerForm.DocumentViewer1.ThumbnailPane.TNViewer1.TNImage(0))
Delegate Sub AddControlToTabControlCallback(ByVal key As String, ByVal tnimage As UeWIImageX.UeWIImage)
Public Sub AddControlToTabControl(ByVal key As String, ByVal tnimage As UeWIImageX.UeWIImage)
' Calling from another thread? -> Use delegate.
If Me.TabControl1.InvokeRequired Then
Dim d As New AddControlToTabControlCallback(AddressOf AddControlToTabControl)
' Execute delegate in the UI thread, pass args as an array.
Me.TabControl1.Invoke(d, New Object() {key, tnimage})
Else ' Same thread.
Me.TabControl1.Tabs(key).TabPage.Controls.Add(tnimage)
End If
End Sub
之后我也遇到了同样的错误。如果我在AddControlToTabControl方法中创建相同的控件,那么我可以将该控件添加到Tabcontrol。下面是代码:
Public Sub AddControlToTabControl(ByVal key As String, ByVal tnimage As UeWIImageX.UeWIImage)
' Calling from another thread? -> Use delegate.
If Me.TabControl1.InvokeRequired Then
Dim d As New AddControlToTabControlCallback(AddressOf AddControlToTabControl)
' Execute delegate in the UI thread, pass args as an array.
Me.TabControl1.Invoke(d, New Object() {key, tnimage})
Else ' Same thread.
Dim uewimg As New UeWIImageX.UeWIImage ' creating the same control as tnimage.
uewimg = tnimage
Me.TabControl1.Tabs(key).TabPage.Controls.Add(uewimg) 'able to add this control to the tabcontrol.
End If
End Sub
如何为TnImage控件使用 Invoke 方法,以便将其添加到 Tabcontrol。请有人帮我解决这个问题。