【发布时间】:2011-04-08 17:22:16
【问题描述】:
是否有关于保存/加载 ListView 控件列状态的最佳实践?我想记住列的顺序和大小,以便 ListView 始终保持用户自定义的状态。是否有一些内置的方法来序列化/反序列化 ListView 列宽和顺序?我在 Google 上找不到答案。
【问题讨论】:
是否有关于保存/加载 ListView 控件列状态的最佳实践?我想记住列的顺序和大小,以便 ListView 始终保持用户自定义的状态。是否有一些内置的方法来序列化/反序列化 ListView 列宽和顺序?我在 Google 上找不到答案。
【问题讨论】:
没有内置方法。提取数据并以对您的应用程序有意义的方式将其持久化。
配置设置通常是最简单的。
Best practice to save application settings in a Windows Forms Application
【讨论】:
ObjectListView - 一个围绕 .NET WinForms ListView 的开源包装器 - 具有保持 ListView 状态的方法。看看SaveState() 和RestoreState() 方法。
一般的策略是:
ListView 状态的对象。ListView 的状态要序列化你的状态对象,你需要这样的东西:
using (MemoryStream ms = new MemoryStream()) {
BinaryFormatter serializer = new BinaryFormatter();
serializer.AssemblyFormat = FormatterAssemblyStyle.Simple;
serializer.Serialize(ms, listViewState);
return ms.ToArray();
}
恢复你的状态:
using (MemoryStream ms = new MemoryStream(state)) {
BinaryFormatter deserializer = new BinaryFormatter();
ListViewState listViewState;
try {
listViewState = deserializer.Deserialize(ms) as ListViewState;
} catch (System.Runtime.Serialization.SerializationException) {
return false;
}
// Restore state here
}
唯一棘手的地方是恢复列的顺序。 DisplayIndex 是出了名的挑剔。
【讨论】: