[英]How to save dynamic ListBox items to a text file WP8
我有一个在运行时为空的ListBox,但是项目(Buttons)是动态添加的。 我的解决方案favorite.txt中有一个文本文件,我需要将该ListBox.Items名称保存以供将来显示。 在XAML中,我有2个位于不同行中的列表框中的按钮:
<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);
}
}
我想保存“收藏夹项目”以备将来启动,因为如果我关闭应用程序,则“列表框收藏夹”将再次为空。 类似于函数:
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();
之前每次调用此函数Application.Current.Terminate();
也许还有其他我不知道的方法...也许隔离存储? 就像这里: http : //msdn.microsoft.com/en-us/library/windowsphone/develop/jj681698(v=vs.105).aspx
我认为您必须使用隔离存储:
\\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();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.