I have a ListBox that on run is empty, but the items (Buttons ) are added dynamically. I have a text file in my Solution favorites.txt and I need that ListBox.Items name to be save for future show. In XAML I have 2 Buttons that are placed in different ListBoxes in Line:
<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 :
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();
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
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();
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.