[英]Opening a generic form from another class causes a IWin32Window conversion error
我一直在使用以下代碼,這些代碼將通過在Datagrid單元中單擊按鈕來打開通用表單。 到目前為止,這種方法已經可以正常工作幾個月了,但是我需要以另外兩種形式實現相同的代碼,因此,為了節省重復的代碼,我決定制作一個包裝類來處理此問題,並僅在需要時創建該類的實例。 但是我得到“從類型'ComplexPropertiesFormWrapper' to type 'IWin32Window' is not valid.'
'轉換'ComplexPropertiesFormWrapper' to type 'IWin32Window' is not valid.'
的轉換'ComplexPropertiesFormWrapper' to type 'IWin32Window' is not valid.'
我根本不理解該錯誤,因為它在我的第一個實施版本中起作用。
第一次實施(按預期工作):
Private Sub editorButton_Click(sender As Object, e As EditorButtonEventArgs)
Dim dataObject As New DataObject()
Dim dataObjectType As Type = dataObject.Type
Dim formType As Type = GetType(ManageComplexProperties(Of )).MakeGenericType(dataObjectType)
Dim complexPropertiesForm = Activator.CreateInstance(formType, _
New Object() {dataObject.Value, dataObject.ValueIsList, Nothing, MyBase.UnitOfWorkNH})
If complexPropertiesForm.ShowDialog(Me) = DialogResult.OK Then
dataObject.Value = complexPropertiesForm.GetResult()
End If
complexPropertiesForm.Dispose()
End Sub
第二種實現(獲得如上所述的錯誤):
這是上面修改后的事件處理程序:
Private Sub editorButton_Click(sender As Object, e As EditorButtonEventArgs)
Dim dataObject As New DataObject()
Dim dataObjectType As Type = dataObject.Type
Dim complexPropertiesFormWrapper As New ComplexPropertiesFormWrapper(dataObjectType, dataObject.Value, dataObject.ValueIsList, Nothing, MyBase.UnitOfWorkNH)
complexPropertiesFormWrapper.Show()
dataObject.Value = complexPropertiesFormWrapper.Value
complexPropertiesFormWrapper.Dispose()
End Sub
這是來自ComplexPropertiesFormWrapper類的相關方法:
Public Sub Show()
Dim formType As Type = GetType(ManageComplexProperties(Of )).MakeGenericType(_type)
Dim _manageComplexPropertiesForm = Activator.CreateInstance(formType, _
New Object() {_value, _valueIsList, Nothing, _unitOfWork})
'ERROR OCCURS ON THE FOLLOWING LINE
_result = _manageComplexPropertiesForm.ShowDialog(Me)
If _result = DialogResult.OK Then
_resultValue = _manageComplexPropertiesForm.GetResult()
End If
End Sub
Public Sub Dispose()
_manageComplexPropertiesForm.Dispose()
End Sub
缺少代碼的某些部分,但是它們與表單和類的操作有關,因此不會由此問題引起。
我花了一些時間進行搜索,但在主題欄上找不到關於Windows IntPtr
和控件句柄的引用,這似乎沒有描述我的問題。
有沒有人對此問題有解決方案,和/或對其發生原因的解釋?
歡迎使用VB或C#回答。
諸如“ FormWrapper”之類的名稱將提示問題的根源,這聽起來不像是從Form派生的類。 是實現IWin32Window接口的Form類。 您的班級也必須實現該目標,以使轉換有效。 這樣做並非難事,只需返回包裝表單的Handle屬性即可。 不要考慮完全不包裝Form派生類作為另一個解決方案,通常對此幾乎沒有需要。
遠程的第二個解釋是您重新聲明了IWin32Window,請不要這樣做。
Form.ShowDialog()方法已重載,不接受任何參數或IWin32Window。 您正在調用后一種實現。
您的ComplexPropertiesFormWrapper類是否繼承Form ? 如果不是,則不能將其強制轉換為IWin32Window。
您可以更改它以便它確實繼承自Form或不使用Me參數調用ShowDialog()嗎? 如果是前者,則需要將ComplexPropertiesFormWrapper.Show()聲明為Overloads。
第一種方法:
Public Class ComplexPropertiesFormWrapper
Inherits Form
Public Overloads Sub Show()
Dim f As New Form1
f.ShowDialog(Me)
End Sub
End Class
第二種方法:
Public Class ComplexPropertiesFormWrapper
Public Sub Show()
Dim f As New Form1
f.ShowDialog()
End Sub
End Class
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.