Xamarin Form在SearchBar中触发空字符串上的SearchCommand

时间:2017-06-05 09:34:35

标签: c# xamarin.forms custom-renderer

我在XamarinForm上使用SearchBar,问题是只要搜索栏为空,我按下搜索按钮,就不会触发SearchCommand。

我尝试在此链接上使用自定义渲染器 from xamarin forum但它不起作用。

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);
            };
        }
    }
}

请帮帮我

1 个答案:

答案 0 :(得分:0)

在MVVM中使用行为。 在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>

在你班上:

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

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

}