Home > database >  Xamarin Searchbar with MVVM
Xamarin Searchbar with MVVM

Time:05-04

There are quite a few articles about how to use the Xamarin SearchBar with MVVM pattern. The problem is that all these articles bind the PerformSearch event to an MVVM command.

I think these days, most users expect to see some results as they type and not once they tap "Search". So, I tried using the Xamarin Community Toolkit's EventToCommandBehavior to bind the TextChanged event to my MVVM command. It looks like this:

<SearchBar
   x:Name="CompanySearch"
   Placeholder="Search companies..."
   PlaceholderColor="#777777"
   BackgroundColor="{StaticResource PrimaryBackground}"
   TextColor="{StaticResource SecondaryDark}">
   <SearchBar.Behaviors>
      <xct:EventToCommandBehavior
         EventName="TextChanged"
         Command="{Binding SearchTextChanged}"
         CommandParameter="{Binding Text, Source={x:Reference CompanySearch}}"/>
   </SearchBar.Behaviors>
</SearchBar>

This works nicely UNTIL the user taps "Cancel" on iOS. Then it crashes the app with the following error:

Invalid type for parameter. Expected Type System.String, but received Type Xamarin.Forms.TextChangedEventArgs

enter image description here

That's because the method that handles the search in my model view is expecting string which looks like this:

async Task On_Search_Text_Changed(string keyword)
{
   if(!string.IsNullOrEmpty(keyword) && keyword.Length > 3)
   {
      var data = await _myApi.CompanySearch(keyword);
      if (data != null && data.Count > 0)
         Suggestions = new ObservableRangeCollection<CompanyModel>(data);
   }
}

Any idea how to handle the cancel event with EventToCommandBehavior? I'm also open to another approach for as long as I can perform the search on TextChanged and NOT on PerformSearch.

CodePudding user response:

just wrap it in a try/catch to trap the exception, or try this

async Task On_Search_Text_Changed(object keyword)
{
   if (keyword is string) 
   {
     ...
   }
}
  • Related