How to save user inputed value in TextBox? (WPF, XAML)
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 Text开发者_Go百科Box in WPF?
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)
In addition to what Simon said, WPF also allows you to bind your UI controls directly to your application settings. That way you don't have to manually load them. Just import your project's Properties
namespace into the Window
or UserControl
and use standard Binding
syntax. Here I have defined a User-level setting in my project's Settings named ServerURL
. Here is how I bind to it.
<Window x:Class="YourProjectNamespace.SomeWindow" xmlns:props="clr-namespace:YourProjectNamespace.Properties">
<TextBox Text="{Binding Source={x:Static props:Settings.Default}, Path=ServerURL}" />
</Window>
Remember that you still need to call Settings.Default.Save()
at some point, probably upon Window's Close or whatever is appropriate in your case. Two-way binding DOES update the source automatically (which in this case is Settings
object), but doesn't write it to disk. You have to call Save()
for that purpose.
精彩评论