Xamarin.Forms如何用UserStoppedTypingBehavior获取Entry输入文本
问题
我在学习Xamarin.Forms,想在代码后置中用Xamarin Community Toolkit的UserStoppedTypingBehavior获取并展示用户输入的搜索值。
当前XAML代码:
<?xml version="1.0" encoding="UTF-8" ?> <ContentPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" xmlns:pv="clr-namespace:Xamarin.Forms.PancakeView;assembly=Xamarin.Forms.PancakeView" xmlns:sharedcustom="clr-namespace:xxx.MyClasses.SharedCustom" xmlns:converters="clr-namespace:xxx.MyValueConverter" xmlns:xct="http://xamarin.com/schemas/2020/toolkit" x:Class="xxx.MyPages.MyNews.MyLeafNews"> <Grid> <Entry x:Name="VariableSearchNews"> <Entry.Behaviors> <xct:UserStoppedTypingBehavior Command="{Binding SearchNewsCommand}" StoppedTypingTimeThreshold="2" MinimumLengthThreshold="2"/> </Entry.Behaviors> </Entry> </Grid> </ContentPage>
当前代码后置:
public ICommand SearchNewsCommand { get; } public MyLeafNews() { InitializeComponent(); SearchNewsCommand = new Command<string>(onSearchNews); this.BindingContext = this; } void onsearchNews(string mysearch) { // 在这里展示搜索文本 Console.WriteLine("The user has wrote :"+mysearch); }
需求:触发onsearchNews(string mysearch)方法时拿到用户输入的内容,实现和TextChanged事件中获取e.NewTextValue同等的效果。
TextChanged事件参考代码:
void OnSearcMyNews(System.Object sender, Xamarin.Forms.TextChangedEventArgs e) { var searchTerm = e.NewTextValue; }
解决方法
你现有代码有两个问题导致拿不到输入值:
- 方法名大小写不匹配:初始化Command时传入的委托名是
onSearchNews,实际定义的方法是onsearchNews,回调无法正常触发。 - 未配置Command参数传递:
UserStoppedTypingBehavior不会默认把Entry的Text值传给Command,需要手动绑定参数。
按以下步骤修改即可:
- 调整XAML中Behavior的配置,添加
CommandParameter绑定当前Entry的Text属性,同时修正时间阈值的单位问题:
<xct:UserStoppedTypingBehavior Command="{Binding SearchNewsCommand}" CommandParameter="{Binding Source={RelativeSource AncestorType={x:Type Entry}}, Path=Text}" StoppedTypingTimeThreshold="2000" MinimumLengthThreshold="2"/>
注意:
StoppedTypingTimeThreshold单位是毫秒,你原来写的2代表2毫秒,输入过程中会频繁触发,一般设置15002000(即1.52秒)才符合“用户停止输入”的检测预期。
- 修正代码后置的方法名,保证和委托传入的名称一致:
public ICommand SearchNewsCommand { get; } public MyLeafNews() { InitializeComponent(); SearchNewsCommand = new Command<string>(OnSearchNews); BindingContext = this; } void OnSearchNews(string mysearch) { // 这里的mysearch就是用户输入的搜索文本,和e.NewTextValue效果一致 Console.WriteLine($"The user has wrote: {mysearch}"); }
修改完成后,当用户停止输入达到设定时长、且输入长度满足最小阈值时,OnSearchNews就会自动触发,参数就是当前Entry的输入内容。
内容的提问来源于stack exchange,提问作者hk77
相关产品推荐
相关产品推荐

