将文本框的默认值更改为新值,并在重新打开后存储新值

时间:2012-11-21 21:39:38

标签: wpf vb.net

我有一个文本框(textbox1),当加载WPF窗口时,它使用UserProfile变量在textbox1.text中显示当前用户目录

   Private Sub Window_Loaded(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles MyBase.Loaded
    Dim defaultpath As String = Environment.CurrentDirectory
    Environment.CurrentDirectory = Environment.GetEnvironmentVariable("UserProfile")
    TextBox1.Text = defaultpath

    End Sub

我还有一个按钮,当单击时,使用FolderBrowserDialog浏览文件夹,然后在textbox1.text中显示新的文件夹路径。

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles Button1.Click
    Dim fldDialog As New FolderBrowserDialog()
    fldDialog.RootFolder = Environment.SpecialFolder.Desktop
    fldDialog.ShowDialog()
    Dim filepathstore As String = fldDialog.SelectedPath

    TextBox1.Text = filepathstore
     End Sub

该值现在显示使用FolderBrowserDialog选择的路径。

如何存储此新值,当WPF窗口关闭/重新打开时,显示此新值而不是默认值。 (替换不删除默认值)

文件夹路径的这个新值可以根据需要多次更改。但是,单击重置按钮时,WPF窗口将恢复为默认值。

1 个答案:

答案 0 :(得分:0)

听起来最简单的选择是将值保存到可以随时调用的文件中。下面的代码假设您在调用FormClosing事件时要保存的值是textbox1.text,然后在打开表单时将其加载回textbox1.text。

Private Sub Form1_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
    Dim s As String
    s = TextBox1.Text
    Dim loc As String
    loc = My.Computer.FileSystem.SpecialDirectories.MyDocuments & "/testfile.txt"
    My.Computer.FileSystem.WriteAllText(loc, TextBox1.Text, False)
End Sub

Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    Dim loc As String
    loc = My.Computer.FileSystem.SpecialDirectories.MyDocuments & "/testfile.txt"
    Dim s As String
    s = My.Computer.FileSystem.ReadAllText(loc)
    TextBox1.Text = s
End Sub

如果您对此有疑问,请告诉我:))