WPF应用实现TextBox重启后保留上次输入值的方法
WPF中实现TextBox值持久化(重启后保留输入内容)
方法一:使用WPF应用设置(推荐,快捷省心)
这是WPF内置的持久化方案,无需自己处理文件读写:
- 添加用户级设置
右键项目→属性→设置,新建一个字符串类型的设置,命名为SavedTextBoxValue,范围选择User(应用级设置为只读,无法修改保存)。 - 代码读写设置
先给TextBox命名:
窗口加载时读取保存的值:<TextBox x:Name="InputTextBox" />
窗口关闭时保存当前输入:private void Window_Loaded(object sender, RoutedEventArgs e) { InputTextBox.Text = Properties.Settings.Default.SavedTextBoxValue; }
也可以直接用XAML绑定简化代码,无需手动读写:private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e) { Properties.Settings.Default.SavedTextBoxValue = InputTextBox.Text; Properties.Settings.Default.Save(); }
然后在<TextBox Text="{Binding Source={x:Static Properties:Settings.Default}, Path=SavedTextBoxValue, Mode=TwoWay}" />App.xaml.cs的退出事件里统一保存:protected override void OnExit(ExitEventArgs e) { Properties.Settings.Default.Save(); base.OnExit(e); }
方法二:使用本地文件存储(灵活可控,适合自定义需求)
如果需要更灵活的存储逻辑,可以自己读写本地文件:
- 定义存储路径
选用户目录下的安全路径,避免权限问题:private string SaveFilePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "MyWpfApp", "TextBoxValue.txt"); - 加载时读取文件
private void Window_Loaded(object sender, RoutedEventArgs e) { if (File.Exists(SaveFilePath)) { InputTextBox.Text = File.ReadAllText(SaveFilePath); } } - 关闭时写入文件
private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e) { // 确保目录存在,避免报错 Directory.CreateDirectory(Path.GetDirectoryName(SaveFilePath)); File.WriteAllText(SaveFilePath, InputTextBox.Text); }
注意事项
- 使用应用设置时,必须选
User范围,Application级设置无法修改保存。 - 本地文件存储优先选择
ApplicationData这类用户专属目录,不要存到程序安装目录(会有写入权限问题)。
内容的提问来源于stack exchange,提问作者Rishabh Gupta
相关产品推荐
相关产品推荐

