我正在製作一個「首選項表單」,它將保存所有用戶首選項,以及何時應用/保存我希望將新值傳回主窗體並更新並關閉表單2。在過去,我已經這樣做了這樣的:在表單之間傳遞數據DIRECTLY
Private Sub PreferencesToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles PreferencesToolStripMenuItem.Click
Preferences.Show()
End Sub
,當我點擊「應用/保存」按鈕將其關閉之前,我會轉移所有的數據是這樣的:
form1.textbox.text = form2.textbox.text
這有什麼錯這樣做?
我一直在閱讀是我應該做這樣的:
Private Sub PreferencesToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles PreferencesToolStripMenuItem.Click
Dim dialog As New Preferences
dialog.ShowDialog()
End Sub
當他們點擊「應用/保存」,將採取從Form2的所有的值,並將其存儲在私有變量時(或財產)的窗體2和當窗體關閉然後我會像這樣訪問值:
Private Sub PreferencesToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles PreferencesToolStripMenuItem.Click
Dim dialog As New Preferences
dialog.ShowDialog()
form1.textbox.text = dialog.variable
End Sub
爲什麼會變成這樣這樣做的更好的辦法?
UPDATE ....查看下面的代碼,這只是我將擁有的所有選項的一個小樣本。在序列化時將數據收集到對象中的最佳方式是什麼?
<Serializable>
Public Class Preference
#Region "Properties"
Public Property ScaleLowest As String = "5"
Public Property ScaleHighest As String = "200"
Public Property ScaleInc As String = "5"
Public Property ThickLowest As Double = 0.125
Public Property ThickHighest As Double = 4
Public Property ThickInc As Double = 0.125
Public Property WidthLowest As Double = 0.125
Public Property WidthHighest As Double = 0.6
Public Property WidthInc As Double = 0.125
Public Property LengthLowest As Double = 1
Public Property LengthHighest As Double = 96
Public Property LengthInc As Double = 1
Public Property FractionON As Boolean = False
Public Property DecimalON As Boolean = True
Public Property ColorSelection As String = "Colors"
Public Property FinalColor As String = "255, 255, 0"
Public Property roughColor As String = "255, 255, 100"
Public Property SplashON As Boolean = False
Public Property LogInON As Boolean = False
#End Region
Public Sub New()
'for creating new instance for deserializing
End Sub
Public Sub GatherAllData()
'Save Defaults
SaveSerializeObj()
End Sub
Public Sub SaveSerializeObj()
'Get Changes?????
'Serialize object to a text file.
Dim objStreamWriter As New StreamWriter("C:\Users\Zach454\Desktop\test.xml")
Dim x As New XmlSerializer(Me.GetType)
x.Serialize(objStreamWriter, Me)
objStreamWriter.Close()
End Sub
Public Function LoadSerializeObj() As Preference
'Check if new file need created
If File.Exists("C:\Users\454\Desktop\test.xml") = False Then
SaveSerializeObj()
End If
'Deserialize text file to a new object.
Dim objStreamReader As New StreamReader("C:\Users\454\Desktop\test.xml")
Dim newObj As New Preference
Dim x As New XmlSerializer(newObj.GetType)
newObj = CType(x.Deserialize(objStreamReader), Preference)
objStreamReader.Close()
Return newObj
End Function
如果您有很多用戶選項,您可能希望有一個班負責加載,保存,顯示和編輯它們。然後,任何需要了解「SaveFolder」或其他任何角色的演員都可以從該類中獲取它。一旦你使用OOP,在表單之間傳遞數據很少發生。另外,您最終會使用默認表單實例來敲擊磚牆。 – Plutonix
在form1和form2之外創建一個不同的類? – goomba454
是的。每個用戶選項都可以是一個屬性(或某些情況下的方法),以便其他演員可以在不加載某些表單的情況下獲取所需的任何內容;表單就是應用程序/代碼如何與用戶進行交互。對於一小部分選項,您可以使用內置的'設置' – Plutonix