如何将动态列表框项保存到文本文件WP8

本文关键字:保存 文本 文件 WP8 动态 列表 | 更新日期: 2023-09-27 18:05:47

我有一个ListBox,运行时为空,但项目(按钮)是动态添加的。我在我的解决方案收藏夹。txt中有一个文本文件,我需要这个列表框。要保存以供将来显示的项目名称。在XAML中,我有两个按钮放置在不同的列表框中:

<ListBox x:Name="mainlist" >
    <Button x:Name="but1" / >     
</ListBox>
<ListBox x:Name="favlist" >                         
    <Button x:Name="fav1" Click="Button_Click_2" Tag="but1" />
</ListBox>

在。cs中,我通过fav1搜索but1。标记并将其添加到收藏列表框:

 private void Button_Click_2(object sender, RoutedEventArgs e)
        {
            var button = (Button)sender;
            button.Opacity = 0;
            button.Click -= Button_Click_2;
            object item = mainlist.FindName(button.Tag.ToString());     
                if (item is Button)
                {
                    Button findedBut = (Button)item;
                    Button newbut = new Button();
                    newbut.Name = findedBut.Name;
                    //add this button to other ListBox called Favorites that is empty
                    Favorites.Items.Add(newbut);
                }
            }  

我想保存收藏夹项目为将来启动,因为如果我关闭应用程序的列表框收藏夹是空的。类似于函数:

void updateFavs()
{
// this is not working ((
 using (FileStream S = File.Open((new Uri(@"favorites.txt", UriKind.Relative)), FileMode.Open))
                    {
                        using (StreamWriter st = new StreamWriter(S))
                         {
                            foreach (var aa in Favorites.Items)
                                st.WriteLine(aa.ToString());
                         }
                    }
}

,每次在Application.Current.Terminate();之前调用该函数也许还有其他我不知道的方式…也许是隔离存储?像在这里:http://msdn.microsoft.com/en-us/library/windowsphone/develop/jj681698 (v = vs.105) . aspx

如何将动态列表框项保存到文本文件WP8

我认为你必须使用隔离存储:

''Create file and save data
  using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream("file.txt", FileMode.Create, IsolatedStorageFile.GetUserStoreForApplication()))
            {
                using (StreamWriter writer = new StreamWriter(stream))
                {
                    writer.WriteLine(1);
                    writer.WriteLine("Hello");
                }
            }
''To read from the file
using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream("file.txt", FileMode.Open, IsolatedStorageFile.GetUserStoreForApplication()))
{
    using (StreamReader reader = new StreamReader(stream))
    {
        int number = Convert.ToInt32(reader.ReadLine());
        string text = reader.ReadLine();
    }
}