You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WPF应用实现TextBox重启后保留上次输入值的方法

WPF中实现TextBox值持久化(重启后保留输入内容)

方法一:使用WPF应用设置(推荐,快捷省心)

这是WPF内置的持久化方案,无需自己处理文件读写:

  1. 添加用户级设置
    右键项目→属性→设置,新建一个字符串类型的设置,命名为SavedTextBoxValue,范围选择User(应用级设置为只读,无法修改保存)。
  2. 代码读写设置
    先给TextBox命名:
    <TextBox x:Name="InputTextBox" />
    
    窗口加载时读取保存的值:
    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        InputTextBox.Text = Properties.Settings.Default.SavedTextBoxValue;
    }
    
    窗口关闭时保存当前输入:
    private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
    {
        Properties.Settings.Default.SavedTextBoxValue = InputTextBox.Text;
        Properties.Settings.Default.Save();
    }
    
    也可以直接用XAML绑定简化代码,无需手动读写:
    <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);
    }
    

方法二:使用本地文件存储(灵活可控,适合自定义需求)

如果需要更灵活的存储逻辑,可以自己读写本地文件:

  1. 定义存储路径
    选用户目录下的安全路径,避免权限问题:
    private string SaveFilePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "MyWpfApp", "TextBoxValue.txt");
    
  2. 加载时读取文件
    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        if (File.Exists(SaveFilePath))
        {
            InputTextBox.Text = File.ReadAllText(SaveFilePath);
        }
    }
    
  3. 关闭时写入文件
    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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 14:57:28