数据操作类 有分页
todoitemDatabase.cs:
using SQLite;
using TodoSQLite.Models;namespace TodoSQLite.Data
{public class TodoItemDatabase{SQLiteAsyncConnection Database;public TodoItemDatabase(){}// 初始化数据库连接和表async Task Init(){if (Database is not null)return;// 创建数据库连接并创建 TodoItem 表Database = new SQLiteAsyncConnection(Constants.DatabasePath, Constants.Flags);var result = await Database.CreateTableAsync<TodoItem>();}// 获取所有 TodoItempublic async Task<List<TodoItem>> GetItemsAsync(){await Init();return await Database.Table<TodoItem>().ToListAsync();}// 获取所有未完成的 TodoItempublic async Task<List<TodoItem>> GetItemsNotDoneAsync(){await Init();return await Database.Table<TodoItem>().Where(t => t.Done).ToListAsync();}// 获取分页的 TodoItem 和总记录数public async Task<(List<TodoItem> items, int totalCount)> GetItemsPageAsync(int pageNumber, int pageSize){await Init();var items = await Database.Table<TodoItem>().Skip((pageNumber - 1) * pageSize).Take(pageSize).ToListAsync();var totalCount = await Database.Table<TodoItem>().CountAsync(); // 获取总记录数return (items, totalCount);}// 获取分页的未完成 TodoItem 和总记录数public async Task<(List<TodoItem> items, int totalCount)> GetItemsNotDonePageAsync(int pageNumber, int pageSize){await Init();var items = await Database.Table<TodoItem>().Where(t => t.Done).Skip((pageNumber - 1) * pageSize).Take(pageSize).ToListAsync();var totalCount = await Database.Table<TodoItem>().Where(t => t.Done).CountAsync(); // 获取总记录数return (items, totalCount);}// 根据 ID 获取 TodoItempublic async Task<TodoItem> GetItemAsync(int id){await Init();return await Database.Table<TodoItem>().Where(i => i.ID == id).FirstOrDefaultAsync();}// 保存或更新 TodoItempublic async Task<int> SaveItemAsync(TodoItem item){await Init();if (item.ID != 0){return await Database.UpdateAsync(item);}else{return await Database.InsertAsync(item);}}// 删除 TodoItempublic async Task<int> DeleteItemAsync(TodoItem item){await Init();return await Database.DeleteAsync(item);}}
}
TodoItem.cs 相当于实体类
using SQLite;namespace TodoSQLite.Models;public class TodoItem
{[PrimaryKey, AutoIncrement]public int ID { get; set; }//主键public string Name { get; set; }//任务名public string Notes { get; set; }//备注public bool Done { get; set; }//完成否}
##界面
任务例表界面代码:
<?xml version="1.0" encoding="utf-8" ?>
<ContentPagex:Class="TodoSQLite.Views.TodoListPage"xmlns="http://schemas.microsoft.com/dotnet/2021/maui"xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"xmlns:ios="clr-namespace:Microsoft.Maui.Controls.PlatformConfiguration.iOSSpecific;assembly=Microsoft.Maui.Controls"xmlns:models="clr-namespace:TodoSQLite.Models"Title="任务"ios:Page.UseSafeArea="True"><Grid RowDefinitions="*,Auto"><CollectionViewItemsSource="{Binding Items}"SelectionChanged="CollectionView_SelectionChanged"SelectionMode="Single"VerticalOptions="Fill"><CollectionView.ItemTemplate><DataTemplate x:DataType="models:TodoItem"><GridPadding="20"ColumnDefinitions="*, Auto"RowDefinitions="Auto"><Label Text="{Binding Name}" VerticalTextAlignment="Center" /><LabelGrid.Column="1"IsVisible="{Binding Done}"Text="✔️"VerticalTextAlignment="Center" /></Grid></DataTemplate></CollectionView.ItemTemplate></CollectionView><ButtonGrid.Row="1"Margin="20"Clicked="OnItemAdded"Text="增加" /></Grid>
</ContentPage>
对应的C#
using System.Collections.ObjectModel;
using TodoSQLite.Data;
using TodoSQLite.Models;namespace TodoSQLite.Views
{public partial class TodoListPage : ContentPage{public ObservableCollection<TodoItem> Items { get; set; } = new();private int pageNumber = 1; // 默认页码private int pageSize = 10; // 默认页面大小TodoItemDatabase database;public TodoListPage(TodoItemDatabase todoItemDatabase){InitializeComponent();database = todoItemDatabase;BindingContext = this;}// 当页面导航到前台时触发protected override async void OnNavigatedTo(NavigatedToEventArgs args){base.OnNavigatedTo(args);// 获取所有 TodoItem 并刷新界面var items = await database.GetItemsAsync();MainThread.BeginInvokeOnMainThread(() =>{Items.Clear();foreach (var item in items)Items.Add(item);});}// 加载分页数据private async void LoadData(){var (items, _) = await database.GetItemsPageAsync(pageNumber, pageSize);MainThread.BeginInvokeOnMainThread(() =>{Items.Clear();foreach (var item in items)Items.Add(item);});}// 加载分页的未完成数据private async void LoadDataNotDone(){var (items, _) = await database.GetItemsNotDonePageAsync(pageNumber, pageSize);MainThread.BeginInvokeOnMainThread(() =>{Items.Clear();foreach (var item in items)Items.Add(item);});}// 点击上一页按钮时触发的事件处理private void OnPreviousPageClicked(object sender, EventArgs e){if (pageNumber > 1){pageNumber--;LoadData();}}// 点击下一页按钮时触发的事件处理private void OnNextPageClicked(object sender, EventArgs e){pageNumber++;LoadData();}// 点击添加按钮时触发的事件处理async void OnItemAdded(object sender, EventArgs e){await Shell.Current.GoToAsync(nameof(TodoItemPage), true, new Dictionary<string, object>{["Item"] = new TodoItem()});}// 列表项选择变更时触发的事件处理private async void CollectionView_SelectionChanged(object sender, SelectionChangedEventArgs e){if (e.CurrentSelection.FirstOrDefault() is not TodoItem item)return;// 导航到 TodoItemPage 传递选中的 TodoItemawait Shell.Current.GoToAsync(nameof(TodoItemPage), true, new Dictionary<string, object>{["Item"] = item});}}
}
详情 页:
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"x:Class="TodoSQLite.Views.TodoItemPage"Title="{Binding Name}"xmlns:models="clr-namespace:TodoSQLite.Models"x:DataType="models:TodoItem"><ScrollView><VerticalStackLayout Padding="20"Spacing="10"VerticalOptions="StartAndExpand"><Label Text="任务名" /><Entry Text="{Binding Name}" /><Label Text="备注" /><Entry Text="{Binding Notes}" /><Label Text="完成" /><Switch IsToggled="{Binding Done}" /><Button Text="保存"Clicked="OnSaveClicked" /><Button Text="删除"Clicked="OnDeleteClicked" /><Button Text="取消"Clicked="OnCancelClicked" /></VerticalStackLayout></ScrollView>
</ContentPage>
C#
using TodoSQLite.Data;
using TodoSQLite.Models;namespace TodoSQLite.Views
{[QueryProperty("Item", "Item")] // 通过 URI 查询参数传递 TodoItem 实例public partial class TodoItemPage : ContentPage{public TodoItem Item{get => BindingContext as TodoItem; // 使用 BindingContext 获取 TodoItemset => BindingContext = value; // 设置 BindingContext 以更新页面数据绑定}TodoItemDatabase database;public TodoItemPage(TodoItemDatabase todoItemDatabase){InitializeComponent();database = todoItemDatabase;}// 点击保存按钮时触发的事件处理async void OnSaveClicked(object sender, EventArgs e){if (string.IsNullOrWhiteSpace(Item.Name)){await DisplayAlert("任务名", "请增加任务名", "OK");return;}// 保存或更新 TodoItem 数据await database.SaveItemAsync(Item);// 返回上一页await Shell.Current.GoToAsync("..");}// 点击删除按钮时触发的事件处理async void OnDeleteClicked(object sender, EventArgs e){// 如果 TodoItem 的 ID 为 0,表示未保存到数据库,直接返回if (Item.ID == 0)return;// 删除 TodoItem 数据await database.DeleteItemAsync(Item);// 返回上一页await Shell.Current.GoToAsync("..");}// 点击取消按钮时触发的事件处理async void OnCancelClicked(object sender, EventArgs e){// 返回上一页await Shell.Current.GoToAsync("..");}}
}
下载代码