>Ciao a tutti,
>vi scrivo perché vorrei capire come passare il valore di una
>proprietà pubblica di una form quando quest'ultima è stata dichiarata
>come form generica.
>Mi spiego meglio con un esempio
>
>Dim frm as New Form
>frm = GetFormByName(nomeform) ' dove questa funzione mi recupera
>effettivamente la form che mi serve
>'questa è la parte incriminata
>frm.miaproprieta = "PIPPO"
>La proprietà miaproprietà è dichiarata pubblica sulla form chiamata
>ma ovviamente dichiarando la form in modo generico, questa proprietà
>non me la vede.
>
>Avete qualche soluzione cercando di evitare variabili globali
>e cose del tipo dim frm as new frmMiaForm
>
>Grazie per la vostra disponibilità
Ovviamente se non conosci a priori il tipo di form (magari tra diversi tipi) non puoi fare ne cast ne dichiararlo nel codice...
Una soluzione pulita potrebbe essere quella di usare un interfaccia comune a tutti i form nel caso tutti abbiano una proprietà identica, a quel punto fai un cast sul tipo interfaccia, oppure usi la reflection :
Interfaccia :
Public Interface IMyForm
Property MyProperty As String
End Interface
Public Class MyForm1
Implements IMyForm
Dim _Property As String
Property MyProperty As String Implements IMyForm.MyProperty
Get
MyProperty = _Property
End Get
Set(value As String)
_Property = value
End Set
End Property
End Class
Public Class MyForm2
Implements IMyForm
Dim _Property As String
Property MyProperty As String Implements IMyForm.MyProperty
Get
MyProperty = _Property
End Get
Set(value As String)
_Property = value
End Set
End Property
End Class
....
'dichiaro tipi di form diversi
Dim f1 = New MyForm1()
Dim f2 = New MyForm2()
'dichiaro un tipo IMyForm che potra contenere qualsiasi form che implementa
'IMyForm
Dim MyForm As IMyForm
'ora posso fare un cast da qualsiasi tipo di form
'prima con MyForm1
MyForm = DirectCast(f1, IMyForm)
MyForm.MyProperty = "Nuovo valore"
'poi con MyForm2
MyForm = DirectCast(f2, IMyForm)
MyForm.MyProperty = "Nuovo valore"
Reflection (senza l'uso delle interfacce)
Public Sub SetMyProperty(ByVal NomeTipo As String, ByVal Valore As String)
Dim asm = Assembly.GetExecutingAssembly()
Dim MioNameSpace = asm.FullName.Split(Char.Parse(","))(0)
Dim tipo As Type = asm.GetType(String.Format("{0}.{1}", MioNameSpace, NomeTipo))
Dim window = Nothing
For Each win In Application.Current.Windows
If (win.GetType() = tipo) Then
window = win
Exit For
End If
Next
If (window Is Nothing) Then
Return
End If
tipo.GetProperty("MyProperty").SetValue(window, Valore)
End Sub
....
SetMyProperty("MyForm1", "Nuovo valore")
ovviamente con la reflection devi stare attento che il tipo di form possieda MyProperty...