SearchBar unfocus automatically after using TextChanged event in Xamarin Forms

Viewed 979

I have a simple search-bar component and its TextChanged event

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

In SearchBar_TextChanged() method I try to find data by text and assign it to the item source. Everything works fine but the problem is that the search-bar gets unfocused after the filter.

  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()));
        }
2 Answers

You could try to let your searchbar focus manually.

 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()));
        }
        SearchBar.Focus();
    }

the issue seems to occure when you are using the SearchBar in a Collection\ListView's Header, so just move to outside of it.

Related