私はVB.NETとWPFが初めてです。
「アンケート」アプリを構築しています。ユーザーには、さまざまな質問/タスク (ウィンドウ) が順番に表示されます。各質問/タスクに回答して「送信」ボタンを押すと、新しいウィンドウが開き、新しい質問/タスクが表示され、前のウィンドウが閉じます。各質問の後、ボタンが押されたときに、データを何らかのグローバル オブジェクトに保存する必要があります。すべての質問に回答した後、このオブジェクトのデータを出力ファイルに書き出す必要があります。
各ウィンドウの後に結果を保存するには Dictionary が最適であることがわかりました。
このグローバル ディクショナリを作成する方法、場所、アクセス方法がわかりません。ビューモデルを使用する必要がありますか? はいの場合、例を挙げていただけますか?それとも、共有プロパティを持つ単純なクラスにする必要がありますか? (このようなもの)
編集2:オンラインで推奨されるさまざまな方法を試しました
グローバルモジュール:
Module GlobalModule
Public Foo As String
End Module
グローバル変数:
Public Class GlobalVariables
Public Shared UserName As String = "Tim Johnson"
Public Shared UserAge As Integer = 39
End Class
グローバル プロパティ:
Public Class Globals
Public Shared Property One As String
Get
Return TryCast(Application.Current.Properties("One"), String)
End Get
Set(ByVal value As String)
Application.Current.Properties("One") = value
End Set
End Property
Public Shared Property Two As Integer
Get
Return Convert.ToInt32(Application.Current.Properties("Two"))
End Get
Set(ByVal value As Integer)
Application.Current.Properties("Two") = value
End Set
End Property
End Class
これは、最初のウィンドウでデータをグローバル変数/プロパティに保存する場所です。古いウィンドウを閉じて新しいウィンドウを開く前に、このサブルーチンにデータを保存する必要があります。テストのためだけに MessageBox を使用します。
Private Sub btnEnter_Click(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnEnter.Click
Dim instructionWindow As InstructionsWindow
instructionWindow = New InstructionsWindow()
Application.Current.Properties("number") = textBoxValue.Text
Globals.One = "2"
Globals.Two = 3
MessageBox.Show("GlobalVariables: UserName=" & GlobalVariables.UserName & " UserAge=" & GlobalVariables.UserAge)
GlobalVariables.UserName = "Viktor"
GlobalVariables.UserAge = 34
GlobalModule.Foo = "Test Foo"
'testing if it saved tha value
'MessageBox.Show(Application.Current.Properties("number"))
Application.Current.MainWindow.Close()
instructionWindow.ShowDialog()
End Sub
次のサブルーチンは、2 番目のウィンドウでグローバル プロパティ/変数から値を取得しようとしているところですが、メッセージ ボックスは空になります。また、間違った方法で値を代入している、または正しい方法で値を読み取っていない (キャスト?) 場合もあります。
Private Sub FlowDocReader_Initialized(ByVal sender As Object, ByVal e As System.EventArgs) Handles FlowDocReader.Initialized
' Get a reference to the Application base class instance.
Dim currentApplication As Application = Application.Current
MessageBox.Show(currentApplication.Properties("number"))
MessageBox.Show("One = " & Globals.One & " Two = " & Globals.Two)
MessageBox.Show("GlobalVariables: UserName=" & GlobalVariables.UserName & " UserAge=" & GlobalVariables.UserAge)
MessageBox.Show("GlobalModule.Foo = " & GlobalModule.Foo)
Dim filename As String = My.Computer.FileSystem.CurrentDirectory & "\instructions.txt"
Dim paragraph As Paragraph = New Paragraph()
paragraph.Inlines.Add(System.IO.File.ReadAllText(filename))
Dim document As FlowDocument = New FlowDocument(paragraph)
FlowDocReader.Document = document
End Sub
ありがとう。