Reputation: 185
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
Upvotes: 5
Views: 2948
Reputation: 61
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.
}
}
Upvotes: 6