【发布时间】:2011-02-22 19:59:50
【问题描述】:
我的表单上有一个列表框,我想保存它并在我再次启动应用程序时加载值。
如何在PrjName.Properties.Settings.Default 上保存列表?
【问题讨论】:
我的表单上有一个列表框,我想保存它并在我再次启动应用程序时加载值。
如何在PrjName.Properties.Settings.Default 上保存列表?
【问题讨论】:
没问题! 创建一个新设置,例如“MyListOfStrings”,类型无关紧要。
然后在 xml 编辑器中打开设置文件
您的文件将如下所示:
现在如下图修改并保存
好吧,就是这样,现在它看起来像这样:
在代码中:
【讨论】:
MyListOfStrings是这样定义的,是否可以在Visual Studio IDE中使用编辑器访问?
the property could not be created from it's default value, there is an error in XML document (1,1) 异常。可能是什么问题?我尝试将默认值设置为字符串(红色、蓝色...)并使用十六进制(#FFFF00FF...)但没有成功。
<?xml version="1.0" encoding="utf-16"?> <ArrayOfString xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <string1> <string2> </ArrayOfString>
.Save() 方法仅在您修改列表本身时才有效(例如 .Add 或 .Remove) ,如果您想在修改列表中已有对象的 content 后保存,只需像这样重新加载列表:Properties.Settings.Default.List = Properties.Settings.Default.List;,然后再调用.Save(),它将正常工作。这与设置类如何处理检测更改以避免一遍又一遍地将相同的设置写入磁盘有关。
在应用设置上发现不能直接保存List<string>,但是看到可以保存StringCollection。
而here 我发现从StringCollection 转换为List<string> 非常简单
var list = stringCollection.Cast<string>().ToList();
【讨论】:
Dim list = stringCollection.Cast(Of String)().ToList()的VB.NET项目;我有旧版应用程序需要支持,这非常有用/非常简单。我使用ToArray 和String.Join,但相同的区别。
我知道这是一个较老的问题,但我觉得值得注意的是,您可以创建一个自定义类来继承您想要使用的任何类型的列表,并且设置起来非常简单。例如,如果你想要一个List<CustomData>,你可以这样创建类:
using System.Collections.Generic;
namespace YourNamespace
{
public class CustomCollection : List<CustomData>
{
}
}
然后打开@pr0gg3r 建议的设置并将其添加到<Settings> 部分:
<Setting Name="SomeSetting" Type="YourNamespace.CustomCollection" Scope="User">
<Value Profile="(Default)" />
</Setting>
您将无法使用设置设计器,除非它是字符串或 int 等基本数据类型。如果您使用的是自定义数据类型,则必须在启动时对其进行初始化,然后再使用它,但我发现它看起来仍然比尝试在设置中直接使用列表更优雅。
【讨论】:
使用本机支持的类型 System.Collections.Specialized.StringCollection 时
我使用了这个代码:
System.Collections.Specialized.StringCollection SavedSearchTerms = new System.Collections.Specialized.StringCollection();
if (Properties.Settings.Default.SavedSearches != null)
{
SavedSearchTerms = Properties.Settings.Default.SavedSearches;
}
SavedSearchTerms.Add("Any Value");
Properties.Settings.Default.SavedSearches = SavedSearchTerms;
【讨论】: