C# WinForm设置未保存
我使用VSTO内置设置文件来保存Windows应用程序设置C# WinForm设置未保存,c#,winforms,settings,C#,Winforms,Settings,我使用VSTO内置设置文件来保存Windows应用程序设置 private void MyFormLoad(object sender, EventArgs e) { //Find the appropriate property in the Settings file System.Configuration.SettingsProperty property; property = P_Settings.Settings.Default.P
private void MyFormLoad(object sender, EventArgs e)
{
//Find the appropriate property in the Settings file
System.Configuration.SettingsProperty property;
property = P_Settings.Settings.Default.Properties[checkBox.Name];
if (property != null)
checkBox.Checked = Convert.ToBoolean(property.DefaultValue);
}
我在WinForm上有一个复选框,而在加载表单时我读取它的状态(选中或未选中)
从设置文件中的相应属性
只要我不退出应用程序,这就可以正常工作。但是,当我退出并再次执行应用程序时,设置不会从上次执行保存,复选框状态也不会作为上次首选项 我使用“用户”范围保存设置
private void MyFormLoad(object sender, EventArgs e)
{
//Find the appropriate property in the Settings file
System.Configuration.SettingsProperty property;
property = P_Settings.Settings.Default.Properties[checkBox.Name];
if (property != null)
checkBox.Checked = Convert.ToBoolean(property.DefaultValue);
}
加载表单时,从设置中提取复选框状态
private void MyFormLoad(object sender, EventArgs e)
{
//Find the appropriate property in the Settings file
System.Configuration.SettingsProperty property;
property = P_Settings.Settings.Default.Properties[checkBox.Name];
if (property != null)
checkBox.Checked = Convert.ToBoolean(property.DefaultValue);
}
在表单关闭时,将设置文件与表单状态同步
private void ButtonApplyClick(object sender, EventArgs e)
{
System.Configuration.SettingsProperty property;
property = P_Settings.Settings.Default.Properties[checkBox.Name];
property.DefaultValue = checkBox.Checked.ToString();
P_Settings.Settings.Default.Save();
}
我认为不应该在此处存储设置属性的值。这看起来更像是属性定义的一部分(在应用程序运行期间应该保持不变,因此应该是硬编码的),而不是将随设置一起保存的内容
相反,请尝试直接使用:
加载:
object propValue = P_Settings.Settings.Default[checkBox.Name];
if (propValue != null) {
checkBox.Checked = Convert.ToBoolean(propValue);
}
P_Settings.Settings.Default[checkBox.Name] = checkBox.Checked.ToString();
P_Settings.Settings.Default.Save();
保存:
object propValue = P_Settings.Settings.Default[checkBox.Name];
if (propValue != null) {
checkBox.Checked = Convert.ToBoolean(propValue);
}
P_Settings.Settings.Default[checkBox.Name] = checkBox.Checked.ToString();
P_Settings.Settings.Default.Save();
编辑:最初,您将复选框状态存储在设置属性的DefaultValue
属性中。DefaultValue
用于提供默认值,如果在存储的设置中找不到任何设置值,则将返回该默认值。它不是与设置一起存储的值,因为它不应该是用户定义的,也不应该在应用程序运行期间更改
因此,您之前的尝试导致了观察到的行为:您可以为
DefaultValue
分配一个值,该值将在应用程序处于活动状态时保持不变,但该值不会在p\u Settings.Settings.Default.Save()
或在应用程序启动时恢复,因此,在下次启动应用程序时,DefaultValue
将再次具有其默认值(可能是null
)。非常感谢!那太好了!你能补充一些进一步的解释吗?这样我也能理解为什么原始代码不起作用。提前谢谢@user3165438:我对我认为发生的事情添加了一个额外的解释。真的有道理!谢谢!