C# – How to save user inputed value in TextBox? (WPF, XAML)

cnettextboxwpfxaml

How to save user inputed value in a TextBox? (WPF XAML) So in my xaml window I have a TextBox. A User starts my application, inputs some values into it and presses a button or hits Enter. He closes the app, opens it up again. How to make his inputs to be saved in that TextBox in WPF?

Best Answer

You can use the built in .net settings.

In visual studio, right click on your project and choose Add new item. From the dialog, select "Settings file", and give it a name like "MySettings". Visual studio will create a few files including a MySettings class with some static methods to provide you access to your settings.

If you open this file up, you will be given a nice grid ui that allows you to enter some settings, set their type (in this case String) and set a default value. It also allows you to specify if they are application or user settings.

  • Application settings: Cannot be modified after the app has started. Can only be configued by editing an xml .config file. Will be the same for every user who runs the app.
  • User settings: Can be modified and saved while the application is running. Will be stored in the users documents and settings\username\local settings folder. Can be different for every user.

For what you are describing, choose "User" for the scope.

Now, to access the value in code:

// Load the value into the text box.
txtBox1.text = MySettings.Default.SomeSetting;

and to save a change:

// Update the value.
MySettings.Default.SomeSetting = txtBox1.text;

// Save the config file.
MySettings.Default.Save();

There's more information about all of this on MSDN here, and there is more information on the ApplicationSettingsBase class here.

(Obviously, if you are using mvvm, or any other UI pattern you can adapt this code to load the settings values into your model/viewmodels whenever it's appropriate rather than directly into the text box)