Xamarin.Forms中点击按钮删除SQLite数据库指定数据的实现方法
实现步骤
1. 修改XAML页面代码
首先给ListView开启单选模式,支持选中要删除的条目:
<?xml version="1.0" encoding="utf-8" ?> <ContentPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="SP.LoginPage"> <ContentPage.ToolbarItems> <ToolbarItem x:Name="DeleteButton" Text="Delete" Clicked="DeleteButton_Clicked"> </ToolbarItem> </ContentPage.ToolbarItems> <ContentPage.Content> <!-- 新增SelectionMode属性开启单选 --> <ListView x:Name="userData" SelectionMode="Single"> <ListView.ItemTemplate> <DataTemplate> <TextCell Text="{Binding Id}"/> </DataTemplate> </ListView.ItemTemplate> </ListView> </ContentPage.Content> </ContentPage>
2. 补全C#后端删除逻辑
删除按钮点击事件的逻辑为:判断是否选中条目 → 拿到选中条目的ID → 连接数据库执行删除 → 刷新列表数据和数据库同步:
namespace SP { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class LoginPage : ContentPage { public LoginPage() { InitializeComponent(); } protected override void OnAppearing() { base.OnAppearing(); RefreshUserList(); } // 抽离列表刷新逻辑,避免重复写代码 private void RefreshUserList() { using (SQLite.SQLiteConnection conn = new SQLite.SQLiteConnection(App.FilePath)) { conn.CreateTable<SignInInformation>(); var info = conn.Table<SignInInformation>().ToList(); userData.ItemsSource = info; } } void DeleteButton_Clicked(object sender, EventArgs e) { // 没有选中条目直接返回,可选加提示框 if (userData.SelectedItem is not SignInInformation selectedUser) { DisplayAlert("提示", "请先选择要删除的用户条目", "确认"); return; } using (SQLite.SQLiteConnection conn = new SQLite.SQLiteConnection(App.FilePath)) { // 按主键ID删除选中条目 conn.Delete<SignInInformation>(selectedUser.Id); } // 删除完成后刷新列表 RefreshUserList(); // 清空选中状态 userData.SelectedItem = null; } } }
额外说明
如果要实现点击条目旁的删除按钮单独删除,只需要把删除按钮放到DataTemplate的单元格里,用CommandParameter绑定当前条目Id即可,当前逻辑是通用的选中后点顶部删除按钮的实现,完全适配你现有代码结构。重复的列表加载逻辑已单独抽成方法,后续修改列表加载规则只需要改这一处即可。
内容的提问来源于stack exchange,提问作者Mohammad Ishtiaq
相关产品推荐
相关产品推荐

