简体   繁体   English

如何将列表框项目保存为.config文件并将其读回列表框?

[英]how to save listbox item as .config file and read it back to listbox?

In my WPF project, I have a listbox that I can add some items to it in this way: 在我的WPF项目中,我有一个列表框,可以通过这种方式向其中添加一些项目:

//item is a class type of Product
var item = GetProductByID(ProductID);
lb_Configuration.Items.Add(item);

Now I want to save the listbox items when I close this application as a config file and when I reopen it, I can reload this config file to application thus to add the corresponding items to the listbox, how should I suppose to do this? 现在,当我关闭该应用程序作为配置文件时,我想保存列表框项目,当我重新打开它时,我可以将该配置文件重新加载到应用程序中,从而将相应的项目添加到列表框中,我应该怎么做呢? Thanks in advance! 提前致谢!

Edit : 编辑

    private void OpenFile_Executed(object sender, ExecutedRoutedEventArgs e)
    {
        OpenFileDialog openFile = new OpenFileDialog();
        openFile.Multiselect = true;
        openFile.Title = "Please Choose Your File";
        openFile.Filter = "All Files(*,*)|*.*";
        if (openFile.ShowDialog() == true)
        {
            /* What to do after open file */
            StreamReader sr = File.OpenText(openFile.FileName);
            while (sr.EndOfStream != true) ;
        }
    }

    private void SaveFile_Executed(object sender, ExecutedRoutedEventArgs e)
    {
        SaveFileDialog saveFile = new SaveFileDialog();
        saveFile.Filter = "Text File|*.txt";
        if (saveFile.ShowDialog() == true)
        {
            StreamWriter sw = File.AppendText(saveFile.FileName);
            sw.Flush();
            sw.Close();
        }
    }

An exact working answer can't be given since we don't know the make-up of the type Product , but the bottom line here is serialization - which may be extremely simple, or could get more complicated depends on the types used and exposed by the type Product . 由于我们不知道Product类型的组成,因此无法给出确切的工作答案,但是最重要的是序列化-这可能非常简单,或者可能变得更复杂,具体取决于使用和公开的类型按Product类型。 There are numerous tools for this: JSON.net, ServiceStack, and even built-in .net serialization. 有很多工具可以用于此目的:JSON.net,ServiceStack甚至内置的.net序列化。

For simplicitly and an example, consider using JavaScriptSerializer : 为了简单起见,请考虑使用JavaScriptSerializer

var serializer = new JavaScriptSerializer();
var json = serializer.Serialize(item);

And to do it in the other direction... 并朝另一个方向做...

var item = serializer.Deserialize<Product>(json);

That's a starting point, if nothing else. 如果没有别的,那就是一个起点。 Obviously adjust it to serialize the whole collection, make sure all the relevant values are being serialized and deserialized and properly, and save to file: 显然要对其进行调整以序列化整个集合,并确保所有相关值均已正确序列化和反序列化,然后保存到文件中:

File.WriteAllText(pathToFile, json);

To read it back: 读回:

var json = File.ReadAllText(pathToFile);

Use txt file in the application directory: 在应用程序目录中使用txt文件:

    public partial class MainWindow : Window
{
    private string fileName = "lst.txt";
    private List<string> lst;
    public MainWindow()
    {
        InitializeComponent();
        this.Closing += (s, e) =>
          {
              File.WriteAllLines(fileName, this.lst);
          };
    }
    //in other events, button click, initialize or change the lst

    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        try
        {
            this.lst = File.ReadAllLines(fileName).ToList();
        }
        catch (Exception)
        {

        }
    }

    //simulate your other changes to the lst
    private void Button_Click(object sender, RoutedEventArgs e)
    {
        if (lst == null)
            lst = new List<string>();
        lst.Add(new Random().Next().ToString());
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM