在我的WPF项目中,我有一个列表框,我可以用这种方式添加一些项目:
//item is a class type of Product
var item = GetProductByID(ProductID);
lb_Configuration.Items.Add(item);
现在我想在将此应用程序作为配置文件关闭时保存列表框项目,当我重新打开它时,我可以将此配置文件重新加载到应用程序,从而将相应的项目添加到列表框中,我应该怎么做这个?提前谢谢!
修改:
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();
}
}
答案 0 :(得分:1)
由于我们不知道Product
类型的构成,因此无法给出确切的工作答案,但这里的底线是序列化 - 这可能非常简单,或者可能变得更复杂取决于类型Product
使用和公开的类型。有很多工具:JSON.net,ServiceStack,甚至是内置的.net序列化。
对于简单和示例,请考虑使用JavaScriptSerializer:
var serializer = new JavaScriptSerializer();
var json = serializer.Serialize(item);
要从另一个方向去做......
var item = serializer.Deserialize<Product>(json);
这是一个起点,如果没有其他的话。显然调整它以序列化整个集合,确保所有相关值都被序列化和反序列化并正确,并保存到文件:
File.WriteAllText(pathToFile, json);
要读回来:
var json = File.ReadAllText(pathToFile);
答案 1 :(得分:0)
在应用程序目录中使用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());
}
}