Search code examples
c#windows-phone-8observablecollectionisolatedstoragelonglistselector

Writing ObservableCollection to file


What I have:

I currently have this class:

class Storico
{
    private string rigaStorico;

    public string Name
    {
        get { return rigaStorico; }
        set { rigaStorico = value; }
    }

    public Storico(string storic)
    {
        rigaStorico = storic;
    }       
}

This ObservableCollection:

ObservableCollection<Storico> rigaStorico = new ObservableCollection<Storico>();

And this DataTemplate, located into a LongListSelector:

<DataTemplate>
    <Grid>
        <TextBlock Text="●" Margin="0,8,0,0" Foreground="#EE7B00"/>
        <TextBlock Text="{Binding Name}" ManipulationStarted="TextBlock_ManipulationStarted" ManipulationCompleted="TextBlock_ManipulationCompleted">
            <toolkit:ContextMenuService.ContextMenu>
                <toolkit:ContextMenu Name="ContextMenu" >
                    <toolkit:MenuItem Name="DeleteItem" Header="Delete Item" Click="DeleteItem_Click"/>
                </toolkit:ContextMenu>
            </toolkit:ContextMenuService.ContextMenu>
        </TextBlock>
    </Grid>
</DataTemplate>

What I need to do:

I actually need take all the strings contained into the LongListSelector, that may be like:

String1
String2
String3

and write them to a file into IsolatedStorage, in inversed order. Something like this:

String3
String2
String1

Obviously enough, the ItemsSource of the Storico is rigaStorico itself:

Storico.ItemsSource = rigaStorico;

I hope my goal is clear and I gave all the stuff that's needed to solve it.


Solution

  • Thanks for the help. I solved my issue with the following code:


    string[] contenutoStorico = rigaStorico.Select(x => x.Name).ToArray();
    
    IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication();
    using (StreamWriter writeFile = new StreamWriter(new IsolatedStorageFileStream("history.txt", FileMode.Create, FileAccess.Write, myIsolatedStorage)))
    {
        for (int i = 0; i < contenutoStorico.Length; i++)
        {
            writeFile.WriteLine(contenutoStorico[contenutoStorico.Length-i-1]);                    
        }
        writeFile.Close();
    }