正在将ObservableCollection写入文件

本文关键字:文件 ObservableCollection | 更新日期: 2023-09-27 18:00:54

我有什么:

我目前有这样的课程:

class Storico
{
    private string rigaStorico;
    public string Name
    {
        get { return rigaStorico; }
        set { rigaStorico = value; }
    }
    public Storico(string storic)
    {
        rigaStorico = storic;
    }       
}

此可观测集合:

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的物品来源是rigaStorico本身:

Storico.ItemsSource = rigaStorico;

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

正在将ObservableCollection写入文件

试试这个:

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

不确定为什么需要相反的顺序,但您可以使用此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);
    }
}

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


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