[英]How to save dynamic ListBox items to a text file WP8
I have a ListBox that on run is empty, but the items (Buttons ) are added dynamically. 我有一个在运行时为空的ListBox,但是项目(Buttons)是动态添加的。 I have a text file in my Solution favorites.txt and I need that ListBox.Items name to be save for future show.
我的解决方案favorite.txt中有一个文本文件,我需要将该ListBox.Items名称保存以供将来显示。 In XAML I have 2 Buttons that are placed in different ListBoxes in Line:
在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>
Next in .cs I search for but1 by fav1.Tag and add it to Favorites List Box : 接下来在.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);
}
}
And I want to save Favorite Items for future launching because if I close applications the ListBox Favorites is empty again. 我想保存“收藏夹项目”以备将来启动,因为如果我关闭应用程序,则“列表框收藏夹”将再次为空。 Something Like a function:
类似于函数:
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());
}
}
}
and call this functions every time before Application.Current.Terminate();
并在
Application.Current.Terminate();
之前每次调用此函数Application.Current.Terminate();
Or maybe there is other ways that I don't know... maybe Isolated Storage? 也许还有其他我不知道的方法...也许隔离存储? Like here: http://msdn.microsoft.com/en-us/library/windowsphone/develop/jj681698(v=vs.105).aspx
就像这里: http : //msdn.microsoft.com/en-us/library/windowsphone/develop/jj681698(v=vs.105).aspx
I think that you have to use the Isolated Storage: 我认为您必须使用隔离存储:
\\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.