在程序中新建项目(.NET 6.0)
解决方案示例图 如下
默认情况下没有产生配置文件 就是所谓的后缀 settings 文件
实现保存应用程序上的一些用户数据
示例: 保持上次关闭时的窗体位置
步骤1 右键解决方案添加 找到设置文件 并添加
步骤2 打开文件settings 添加您需要保存的变量,数据类型与名称 。(在NET开发环境中不能自定义少见的变量类型,我们可以右键选择XAMl打开)
在打开的XAML 文本编辑器中打开就好(按需求修改) 注在.NET Framework 中 点击下拉框-->择,浏览-->在弹出的窗体输入类型就好
步骤3 在程序关闭时记录当前位置 并写入到文件settings的变量中进行保存 XAML 代码如下
<Window
x:Class="WPF_settings_文件.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:WPF_settings_文件"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
Title="MainWindow"
Width="800"
Height="450"
Closing="Window_Closing"
mc:Ignorable="d" ContentRendered="Window_ContentRendered">
<Grid />
</Window>
步骤4 在程序运行之前就在其构造函数中 将变量值赋值给窗体 后端所有代码如下
using System.ComponentModel;
using System.Windows;
namespace WPF_settings_文件
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
//程序加载
//加载的时候将数据进行读取
//this.RestoreBounds = Settings1.Default.WIndowposition; //赋值
//RestoreBounds 是只读的所有我们只能进行 用同类型记录数据在赋值
try
{
Rect rect = Settings1.Default.WIndowposition;
this.Left = rect.Left;
this.Top = rect.Top;
}
catch {}
}
/// <summary>
/// 程序关闭时 不能使用Closed 否者取出的值是无限 保存当前数据
/// </summary>
/// <param name="e"></param>
public void Window_Closing(object sender, CancelEventArgs e)
{
Settings1.Default.WIndowposition = this.RestoreBounds;//将需要的值 赋值给定义好的变量
Settings1.Default.Save();//Save 保存当前的更改
}
}
}
现在在程序的每次关闭的位置,都会被保存,在下一次运行的时候 保持上次关闭时的窗体位置