将ObservableCollection写入文件

时间:2014-04-29 19:30:27

标签: c# windows-phone-8 observablecollection isolatedstorage longlistselector

我有什么:

我目前有这门课程:

class Storico
{
    private string rigaStorico;

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

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

此ObservableCollection:

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

这个DataTemplate,位于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>

我需要做什么:

我实际上需要将所有包含在LongListSelector中的字符串,可能是:

String1
String2
String3

将它们以相反的顺序写入IsolatedStorage的文件中。像这样:

String3
String2
String1

显然,Storico的ItemsSource就是rigaStorico本身:

Storico.ItemsSource = rigaStorico;

我希望我的目标很明确,并且我提供了解决它所需的所有东西。

3 个答案:

答案 0 :(得分:1)

试试这个:

IsolatedStorageFile savegameStorage = IsolatedStorageFile.GetUserStoreForApplication();

IsolatedStorageFileStream fs = null;
using (fs = savegameStorage.CreateFile("FILENAME"))
{
    if (fs != null)
    {
        var index = 0;
        foreach(var rigaStor in rigaStorico.Reverse())
        {
            byte[] bytes = Encoding.UTF8.GetBytes(rigaStor.Name);
            fs.Write(bytes, index, bytes.Length);
            index = bytes.Length;
        }
    }
}

答案 1 :(得分:1)

不确定为什么以相反的顺序需要它们,但您可以使用此FileStorage来写出数据。

FileStorage.WriteSharedData("MyItems.js", rigaStorico.Reverse());

FileStorage使用json.net,如果你想要你可以做:

var storage = IsolatedStorageFile.GetUserStoreForApplication();
using (var fileStream = storage.CreateFile(fileName))
{
    //Write the data
    using (var isoFileWriter = new StreamWriter(fileStream))
    {
        var json = JsonConvert.SerializeObject(rigaStorico.Reverse());
        isoFileWriter.WriteLine(json);
    }
}

答案 2 :(得分:0)

感谢您的帮助。我用以下代码解决了我的问题:


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