Xamarin实现SearchBar与ListView产品名搜索功能及报错修复
Xamarin SearchBar产品搜索功能报错修复
现有编译报错根因
- 报错1:
'ProductData' does not contain a definition for 'GetNotesAsync3'
本质为方法名拼写不匹配:XAML后台交互代码调用的是带s的GetNotesAsync3方法,数据库操作类中实际定义的是不带s的GetNoteAsync3方法,编译器无法找到匹配的方法定义。 - 报错2:
Cannot implicitly convert type 'SQLite.AsyncTableQuery<Project.Models.Product>' to 'System.Threading.Tasks.Task<Project.Models.Product>'
本质为返回值类型不匹配+异步查询未执行:SQLite Async的Where()方法返回的是延迟构造的AsyncTableQuery<Product>查询对象,既没有被执行触发实际数据库查询,原方法声明的返回值类型(单个Task<Product>)也和查询返回的集合结果完全不匹配。
各模块代码修复方案
1. 数据库操作类(ProductData.cs)
替换原错误的查询方法,对齐方法名、修正返回值类型、执行异步查询:
// 方法名与后台调用完全对齐,返回结果为产品集合的异步任务 public Task<List<Product>> GetNotesAsync3(string searchText) { return _database2.Table<Product>() // 增加大小写不敏感的匹配,提升搜索体验 .Where(i => i.NameProduct.ToLower().Contains(searchText.ToLower())) // 调用ToListAsync()真正执行数据库查询,返回可等待的集合任务 .ToListAsync(); }
2. XAML后台交互代码(xaml.cs)
修正原代码的语法错误(原调用行末尾多余的句点),补充搜索防抖逻辑避免高频查询:
// 防抖计时标记,避免输入过程中频繁触发数据库查询 private DateTime _lastSearchTime; protected override async void OnAppearing() { base.OnAppearing(); // 页面显示时加载全量产品列表 listview.ItemsSource = await App.Database2.GetNotesAsync2(); } async private void SearchBar_TextChanged(object sender, TextChangedEventArgs e) { // 300ms防抖窗口,过滤输入过程中的高频触发 if (DateTime.Now - _lastSearchTime < TimeSpan.FromMilliseconds(300)) return; _lastSearchTime = DateTime.Now; listview.BeginRefresh(); if (string.IsNullOrWhiteSpace(e.NewTextValue)) { // 搜索框为空时展示全量产品 listview.ItemsSource = await App.Database2.GetNotesAsync2(); } else { // 按输入文本检索匹配产品,移除原代码行尾多余的句点语法错误 listview.ItemsSource = await App.Database2.GetNotesAsync3(e.NewTextValue.Trim()); } listview.EndRefresh(); }
3. XAML布局优化
移除原布局中未承载任何控件的冗余空Grid,补充SearchBar基础提示属性:
<ContentPage.Content> <StackLayout> <!-- 移除无实际作用的空Grid --> <SearchBar TextChanged="SearchBar_TextChanged" x:Name="Searbar" Placeholder="输入产品名称搜索" CancelButtonColor="Gray"/> <ListView x:Name="listview" HasUnevenRows="True"> <ListView.ItemTemplate> <DataTemplate> <ViewCell> <StackLayout Orientation="Horizontal"> <Image Source="xamarinremovebg.png" HeightRequest="50" WidthRequest="50"/> <StackLayout HorizontalOptions="StartAndExpand"> <Label Text="{Binding NameProduct}" HeightRequest="40" HorizontalOptions="Center" FontSize="20"/> <Label Text="{Binding Detail}" HeightRequest="40" /> </StackLayout> </StackLayout> </ViewCell> </DataTemplate> </ListView.ItemTemplate> </ListView> </StackLayout> </ContentPage.Content>
内容的提问来源于stack exchange,提问作者user14818846
相关产品推荐
相关产品推荐

