【问题标题】:Xamarin Form trigger SearchCommand in SearchBar on empty stringXamarin Form 在空字符串的 SearchBar 中触发 SearchCommand
【发布时间】:2017-11-06 01:07:12
【问题描述】:

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

请帮帮我

【问题讨论】:

  • 我不认为自定义渲染器会有所帮助,但您可以使用 mySearchBar.TextChanged 来触发您的搜索或缓存搜索字符串
  • 这就是我想要避免的。我想实现 MVVM。现在我使用的是使用 searchbarl.unfocused 在视图模型中触发 searchCommand

标签: c# xamarin.forms custom-renderer


【解决方案1】:

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

}

【讨论】:

  • 错误 XLS0414 找不到类型“行为:EventToCommandBehavior”。确认您没有丢失程序集引用并且所有引用的程序集都已构建。
  • @gattsbr 遇到了和你一样的问题。安装了Xamarin.Forms.BehaviorsPack 并用&lt;behaviorsPack:EventToCommandBehaivor 关闭了&lt;behaviors:EventToCommandBehavior,这为我修复了它。 (也导入了xmlns:behaviorsPack="clr-namespace:Xamarin.Forms.BehaviorsPack;assembly=Xamarin.Forms.BehaviorsPack")
猜你喜欢
  • 1970-01-01
  • 2019-04-23
  • 1970-01-01
  • 2011-10-21
  • 2021-09-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多