问题描述
如何将用户输入的值保存在文本框中?(WPF XAML) 所以在我的 xaml 窗口中我有一个文本框.用户启动我的应用程序,在其中输入一些值并按下按钮或按 Enter.他关闭应用程序,再次打开它.如何将他的输入保存在 WPF 中的那个 TextBox 中?
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?
推荐答案
您可以使用内置的 .net 设置.
You can use the built in .net settings.
在 Visual Studio 中,右键单击您的项目并选择添加新项目.从对话框中,选择设置文件",并为其命名,如MySettings".Visual Studio 将创建一些文件,包括带有一些静态方法的 MySettings
类,以便您访问您的设置.
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.
如果你打开这个文件,你会得到一个漂亮的网格用户界面,允许你输入一些设置,设置它们的类型(在本例中为 String
)并设置一个默认值.它还允许您指定它们是应用程序设置还是用户设置.
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.
- 应用设置:应用启动后无法修改.只能通过编辑 xml .config 文件来配置.对于运行该应用的每个用户来说都是一样的.
- 用户设置:可以在应用程序运行时修改和保存.将存储在用户
documents and settingsusernamelocal 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 settingsusernamelocal 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;
并保存更改:
// Update the value.
MySettings.Default.SomeSetting = txtBox1.text;
// Save the config file.
MySettings.Default.Save();
在 MSDN 这里上有更多关于这一切的信息,以及ApplicationSettingsBase 类在这里有更多信息.
There's more information about all of this on MSDN here, and there is more information on the ApplicationSettingsBase class here.
(显然,如果您使用 mvvm 或任何其他 UI 模式,您可以调整此代码以在适当时将设置值加载到模型/视图模型中,而不是直接加载到文本框中)
这篇关于如何在 TextBox 中保存用户输入的值?(WPF、XAML)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!