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

Dap*_*ana 3 c# custom-renderer xamarin.forms

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

我尝试在xamarin 论坛的此链接上使用自定义渲染器, 但它不起作用。

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);
            };
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

请帮我

小智 5

在 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>
Run Code Online (Sandbox Code Playgroud)

在你的课堂上:

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

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

}
Run Code Online (Sandbox Code Playgroud)