首页 > 解决方案 > 在 Xamarin Forms 中使用 TextChanged 事件后,SearchBar 会自动取消焦点

问题描述

我有一个简单的搜索栏组件及其TextChanged事件

   <SearchBar x:Name="SearchBar" Placeholder="Search words..."
                                       CancelButtonColor="Black"
                                       TextColor="Black"
                                       PlaceholderColor="Black"
                                        BackgroundColor="Transparent"
                                       FontSize="Medium"
                               
                                       TextChanged="SearchBar_TextChanged"
                                      />

SearchBar_TextChanged()方法中,我尝试通过文本查找数据并将其分配给项目源。一切正常,但问题是搜索栏在过滤后变得不集中。

  private async void SearchBar_TextChanged(object sender, TextChangedEventArgs e)
        {
            if (string.IsNullOrWhiteSpace(e.NewTextValue))
                words.ItemsSource = await wordRepository.GetAllAsync();
            else
                words.ItemsSource = await wordRepository.Find(x => x.Name.ToLower().Contains(e.NewTextValue.ToLower()));
        }

标签: c#xamarin.formsxamarin.androidsearchbar

解决方案


当您在 Collection\ListView 的 Header 中使用 SearchBar 时,似乎会出现此问题,因此只需移到它之外。


推荐阅读