c# - Xamarin Form 在空字符串的搜索栏中触发搜索命令

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

请帮我

最佳答案

在 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.
    }

}

关于c# - Xamarin Form 在空字符串的搜索栏中触发搜索命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44365887/

相关文章:

javascript - 我如何等待EvaluateJavascript的结果?

c# NodaTime 将日期格式更改为 yyyy-MM-dd HH :mm:ss

c# - 如何从 ContentPage 获取应用版本?

java - p :commandButton action and f:setpropertyactionlistener not invoked in p:columngroup

c# - 使用 OPCDA.NET 工具远程访问 OPC 服务器

c# - 从非 UI 线程更新 ObservableCollection

c# - 如何覆盖 XAMARIN.FORMS 的加载 View

c# - xamarin 表单有音频控制吗

c# - 如何使用自定义渲染器更改 TableSection 文本颜色 - Xamarin.Forms C#

Java/Swing : How to draw a simple bar graph in a custom renderer for a JLabel