【问题标题】:Persisting ListView column order保持 ListView 列顺序
【发布时间】:2011-04-08 17:22:16
【问题描述】:

是否有关于保存/加载 ListView 控件列状态的最佳实践?我想记住列的顺序和大小,以便 ListView 始终保持用户自定义的状态。是否有一些内置的方法来序列化/反序列化 ListView 列宽和顺序?我在 Google 上找不到答案。

【问题讨论】:

    标签: c# winforms listview


    【解决方案1】:

    没有内置方法。提取数据并以对您的应用程序有意义的方式将其持久化。

    配置设置通常是最简单的。

    Best practice to save application settings in a Windows Forms Application

    【讨论】:

      【解决方案2】:

      ObjectListView - 一个围绕 .NET WinForms ListView 的开源包装器 - 具有保持 ListView 状态的方法。看看SaveState()RestoreState() 方法。

      一般的策略是:

      1. 创建一个保存ListView 状态的对象。
      2. 使用格式化程序将该对象序列化为一系列字节
      3. 保留该系列字节
      4. 恢复时,再次使用格式化程序将字节填充到您的状态对象中。
      5. 从您的状态对象中恢复 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 是出了名的挑剔。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-01-15
        • 2021-06-09
        • 1970-01-01
        • 2022-12-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多