You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Xamarin Forms中存储列表?是否支持原生存储方式?

在Xamarin.Forms中存储列表数据的方案

嘿,这个问题问得很实在!在Xamarin.Forms里存储列表数据,确实有几种原生/官方推荐的路子,我给你掰扯清楚:

一、利用Xamarin.Forms原生机制存储列表的可行方法

Xamarin.Forms的原生存储API本身没有直接存列表的接口,但我们可以通过序列化列表为JSON字符串的方式,把列表转成原生API能处理的格式,这完全是可行的原生方案!下面是几种常用方式:

1. 使用Preferences(适合小型轻量列表)

Preferences是Xamarin.Forms原生提供的键值对存储,适合存储简单、体积小的列表(比如用户的设置选项列表)。

首先需要用System.Text.Json或者Newtonsoft.Json把列表序列化为JSON字符串:

// 定义你的数据模型
public class TodoItem
{
    public int Id { get; set; }
    public string Title { get; set; }
    public bool IsCompleted { get; set; }
}

// 准备要存储的列表
List<TodoItem> todoList = new List<TodoItem>
{
    new TodoItem { Id = 1, Title = "买菜", IsCompleted = false },
    new TodoItem { Id = 2, Title = "写代码", IsCompleted = true }
};

// 序列化并存入Preferences
string json = JsonSerializer.Serialize(todoList);
Preferences.Set("SavedTodoList", json);

读取的时候反过来就行:

string savedJson = Preferences.Get("SavedTodoList", string.Empty);
if (!string.IsNullOrEmpty(savedJson))
{
    List<TodoItem> loadedList = JsonSerializer.Deserialize<List<TodoItem>>(savedJson);
    // 用加载后的列表做逻辑处理
}

2. 使用SecureStorage(适合敏感数据列表)

如果你的列表包含敏感信息(比如用户的银行卡信息、隐私设置),可以用原生的SecureStorage,它会在各个平台上使用系统级的安全存储(比如iOS的Keychain、Android的Keystore)。

用法和Preferences类似,只是方法是异步的:

// 存储敏感列表
string json = JsonSerializer.Serialize(sensitiveList);
await SecureStorage.SetAsync("SecureSavedList", json);

// 读取
string savedJson = await SecureStorage.GetAsync("SecureSavedList");
if (!string.IsNullOrEmpty(savedJson))
{
    List<SensitiveItem> loadedList = JsonSerializer.Deserialize<List<SensitiveItem>>(savedJson);
}

3. 使用FileSystem API(适合中等大小的列表)

Xamarin.Forms的FileSystem API可以让你直接操作本地文件,适合存储体积稍大、或者需要自定义存储格式的列表。

// 获取应用专属的存储路径
string filePath = Path.Combine(FileSystem.AppDataDirectory, "todoList.json");

// 序列化并写入文件
string json = JsonSerializer.Serialize(todoList);
File.WriteAllText(filePath, json);

// 读取文件
if (File.Exists(filePath))
{
    string savedJson = File.ReadAllText(filePath);
    List<TodoItem> loadedList = JsonSerializer.Deserialize<List<TodoItem>>(savedJson);
}

二、更适合复杂列表的官方推荐方案

如果你的列表数据量大、需要频繁进行查询、更新、删除等操作,那么官方推荐的SQLite本地数据库会更合适(虽然它是第三方NuGet包,但属于Xamarin生态的官方推荐工具)。

步骤:

  1. 安装NuGet包:sqlite-net-pcl
  2. 定义带主键的数据模型:
public class TodoItem
{
    [PrimaryKey, AutoIncrement]
    public int Id { get; set; }
    public string Title { get; set; }
    public bool IsCompleted { get; set; }
}
  1. 初始化数据库连接:
private SQLiteAsyncConnection _dbConnection;

async Task InitDatabase()
{
    string dbPath = Path.Combine(FileSystem.AppDataDirectory, "TodoDatabase.db3");
    _dbConnection = new SQLiteAsyncConnection(dbPath);
    await _dbConnection.CreateTableAsync<TodoItem>();
}
  1. 存储和读取列表:
// 插入整个列表
await InitDatabase();
await _dbConnection.InsertAllAsync(todoList);

// 读取全部列表数据
List<TodoItem> loadedList = await _dbConnection.Table<TodoItem>().ToListAsync();

// 还能做条件查询,比如获取未完成的项
List<TodoItem> incompleteItems = await _dbConnection.Table<TodoItem>()
                                                    .Where(item => !item.IsCompleted)
                                                    .ToListAsync();

适用场景总结

  • Preferences:小型、简单的列表,不需要复杂操作
  • SecureStorage:包含敏感信息的列表
  • FileSystem:中等大小、需要自定义存储格式的列表
  • SQLite:大数据量、需要查询/更新操作的结构化列表

内容的提问来源于stack exchange,提问作者asv

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 04:09:45