5

I am using a SearchBar on XamarinForm, the problem is whenever the searchbar is empty and I press the search button, the SearchCommand won't be triggered.

I tried using custom renderer on this link from xamarin forum but It does not work.

public class CustomSearchBarRenderer : SearchBarRenderer
{
    protected override void OnElementChanged(ElementChangedEventArgs<SearchBar> e)
    {
        base.OnElementChanged(e);
        if (e.OldElement == null)
        {
            this.Control.QueryTextSubmit += (sender, args) =>
            {
                if (string.IsNullOrEmpty(args.Query) && Element.SearchCommand != null)
                    Element.SearchCommand.Execute(null);
            };
        }
    }
}

please help me

Daprin Wakaliana
  • 175
  • 2
  • 14
  • I don't think custom renderer will help but you can use mySearchBar.TextChanged to either triger your search or cache the search string – Yuri S Jun 05 '17 at 19:17
  • that's what i want to avoid. I want to implement the MVVM. For now what I used is using searchbarl.unfocused to trigger the searchCommand in view model – Daprin Wakaliana Jun 06 '17 at 01:47

1 Answers1

6

In MVVM use behaviors. In XAML:

<SearchBar x:Name="SearchBarVehicles" SearchCommand="{Binding SearchCommand}" Text="{Binding SearchText.Value, Mode=TwoWay}"    SearchCommandParameter="{Binding Text, Source={x:Reference SearchBarVehicles}}" >
    <SearchBar.Behaviors>
        <behaviors:EventToCommandBehavior
            EventName="TextChanged"
            Command="{Binding TextChangeInSearchCommand}"
            />
    </SearchBar.Behaviors>
</SearchBar>

In your class:

public ICommand TextChangeInSearchCommand => new Command(() => SearchInBlank());
private async void SearchInBlank()
{

    if (string.IsNullOrWhiteSpace(SearchText.Value))
    {
        //Your search in blank.
    }

}
NightOwl888
  • 55,572
  • 24
  • 139
  • 212
  • Error XLS0414 The type 'behaviors:EventToCommandBehavior' was not found. Verify that you are not missing an assembly reference and that all referenced assemblies have been built. – gattsbr Jul 02 '20 at 17:57
  • 1
    @gattsbr Ran into the same problem as you. Installed the [Xamarin.Forms.BehaviorsPack](https://www.nuget.org/packages/Xamarin.Forms.BehaviorsPack) and switched out ` – Zach Hall Sep 21 '20 at 21:07