2

我正在尝试从 ListView 序列化数据,然后对其进行反序列化,并因此用保存的数据填充 ListView。

 public List<ListViewItem> SaveListView(ListView LV)
    {
        System.Collections.Generic.List<ListViewItem> lSavedLV = new List<ListViewItem>();

        for (int i = 0; (i <= animalList.Count - 1); i++)
        {
            lSavedLV.Add(LV.Items[i]);
        }

        return lSavedLV;
    }

这是节省部分的合理解决方案吗?如果我打算用这样的序列化数据填充 ListView,这是要走的路吗?这是否是匹配的加载方法:

 public ListView LoadListView(List<ListViewItem> L)
        {
            ListView lv = new ListView();

            for (int i = 0; (i <= (L.Count - 1)); i++)
            {
                ListViewItem lvi = new ListViewItem();
                lvi = ((ListViewItem)(L[i]));
                lv.Items.Add(lvi);
            }

            return lv;
        }

我真的走神了,我一直在尝试一些不同的事情,但似乎 ListView 的加载/填充有问题。是详细视图。想法,提示?

4

2 回答 2

3

不是想在这里光顾,但 ListView 是表示逻辑。ListViewItem 是表示逻辑。你不应该序列化那些。你应该做的是序列化你的数据,而不是它的视觉表示。

为什么没有一个包含要可视化的数据的类?

public class DataIWannaVisualize
{
    // ...
}

通过给它适当的属性使其可序列化:

[Serializable]
public class DataIWannaVisualize

并拥有这些数据对象的列表。

IList<DataIWannaVisualize> dataList = new List<DataIWannaVisualize>();

此列表包含您将要显示的数据、您对其进行更改的数据,等等。当然,它也可以很容易地序列化或反序列化。

using (Stream stream = File.Open("data.bin", FileMode.Create))
{
    BinaryFormatter formatter = new BinaryFormatter();
    formatter.Serialize(stream, dataList);
}

现在,你的 ListView。通过在表单的 Load 事件上设置处理程序来填充它。

private void Form1_Load(object sender, EventArgs e)
{
    foreach (DataIWannaVisualize dataObject in dataList)
    {
        ListViewItem item = new ListViewItem();
        // TODO: Fill the item with the desired data.
        listView1.Items.Add(item);
    }
}

最重要的是,您不必担心序列化 UI 逻辑类。

于 2013-05-07T21:35:46.330 回答
0

卡拉什已经提供了足够的答案,但如果你想看一个完整的例子......

它不是使用 ListView,而是使用 DataGridView ...但它将向您展示如何持久化数据以及如何加载它

using System;
using System.Collections.Generic;
using System.Windows.Forms;

namespace DataExample
{
    public class Form1 : Form
    {
        private string _Filename = "MyAnimals.xml";
        public List<Animal> myAnimals = new List<Animal>();
        public Form1()
        {
            InitializeComponent();
        }

        public void RegisterDog(String name)
        {
            myAnimals.Add(new Dog { Name = name });
        }
        public void RegisterCat(String name)
        {
            myAnimals.Add(new Cat { Name = name });
        }

        private DataGridView dataGridView1;
        private Button button1;
        private Button button2;

        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.dataGridView1 = new System.Windows.Forms.DataGridView();
            this.button1 = new System.Windows.Forms.Button();
            this.button2 = new System.Windows.Forms.Button();
            ((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).BeginInit();
            this.SuspendLayout();
            // 
            // dataGridView1
            // 
            this.dataGridView1.AllowUserToAddRows = false;
            this.dataGridView1.AllowUserToDeleteRows = false;
            this.dataGridView1.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
            this.dataGridView1.Location = new System.Drawing.Point(12, 12);
            this.dataGridView1.Name = "dataGridView1";
            this.dataGridView1.Size = new System.Drawing.Size(260, 199);
            this.dataGridView1.TabIndex = 0;
            // 
            // button1
            // 
            this.button1.Location = new System.Drawing.Point(12, 229);
            this.button1.Name = "button1";
            this.button1.Size = new System.Drawing.Size(85, 21);
            this.button1.TabIndex = 1;
            this.button1.Text = "persist to file";
            this.button1.UseVisualStyleBackColor = true;
            this.button1.Click += new System.EventHandler(this.button1_Click);
            // 
            // button2
            // 
            this.button2.Location = new System.Drawing.Point(151, 229);
            this.button2.Name = "button2";
            this.button2.Size = new System.Drawing.Size(121, 21);
            this.button2.TabIndex = 2;
            this.button2.Text = "make dummy objects";
            this.button2.UseVisualStyleBackColor = true;
            this.button2.Click += new System.EventHandler(this.button2_Click);
            // 
            // Form1
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(284, 262);
            this.Controls.Add(this.button2);
            this.Controls.Add(this.button1);
            this.Controls.Add(this.dataGridView1);
            this.Name = "Form1";
            this.Text = "Form1";
            this.Load += new System.EventHandler(this.Form1_Load);
            ((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).EndInit();
            this.ResumeLayout(false);

        }

        #endregion

        private void button2_Click(object sender, EventArgs e)
        {
            RegisterDog("SomeDog");
            RegisterCat("SomeCat");
            dataGridView1.DataSource = null;
            dataGridView1.DataSource = myAnimals;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                using (System.Xml.XmlWriter xmlWriter = System.Xml.XmlWriter.Create(_Filename))
                {
                    System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(List<Animal>), new Type[] { typeof(Dog), typeof(Cat) });
                    serializer.Serialize(xmlWriter, myAnimals);
                }
            }
            catch { }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            try
            {
                using (System.Xml.XmlReader xmlReader = System.Xml.XmlReader.Create(_Filename))
                {
                    System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(List<Animal>), new Type[] { typeof(Dog), typeof(Cat) });
                    myAnimals = (List<Animal>)serializer.Deserialize(xmlReader);
                    dataGridView1.DataSource = myAnimals;
                }
            }
            catch { }
        }
    }
    [Serializable]
    public abstract class Animal
    {
        public String Name { get; set; }
        public abstract String Species { get; }
    }
    [Serializable]
    public class Dog : Animal
    {

        public override string Species
        {
            get { return "Dog"; }
        }
    }
    [Serializable]
    public class Cat : Animal
    {

        public override string Species
        {
            get { return "Cat"; }
        }
    }

}

如果它真的必须是一个 ListView,你可以使用一个循环,就像 Callash 在他的 Form1_Load(...) 中的循环一样,一旦它被反序列化,就可以从你的数据中创建新的 ListViewItems ...

于 2013-05-07T21:48:25.043 回答