如何将动态ListBox项目保存到文本文件WP8

时间:2014-05-30 08:17:55

标签: c# xaml windows-phone-8 listbox

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

<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.Tag搜索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);
                }

            }  

我想保存收藏的项目以备将来启动,因为如果我关闭应用程序,ListBox收藏夹将再次为空。 像功能一样:

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

1 个答案:

答案 0 :(得分:0)

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

\\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();
    }
}