You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Xamarin Forms 如何在Entry的Text_Changed触发时展示后端预测列表

实现地点输入自动补全提示的方案

步骤1:修改UI布局,新增预测列表展示控件

在原有Entry下方添加ListView(或CollectionView)用于展示返回的预测地点列表,修改后的XML代码如下:

<StackLayout BackgroundColor="BlanchedAlmond" >
    <Entry x:Name="locationEntry"
           TextChanged="locationText_Changed"
           Placeholder="Enter Address"/>
    <!-- 新增预测列表控件 -->
    <ListView x:Name="predictionListView" 
              IsVisible="False" 
              ItemTapped="predictionListView_ItemTapped"
              Margin="0,5,0,0">
        <ListView.ItemTemplate>
            <DataTemplate>
                <TextCell Text="{Binding Description}" />
                <!-- 此处的Description要和你Prediction类里显示地点名称的字段名对应,如果是其他字段自行修改 -->
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>
</StackLayout>

步骤2:修改C#后端逻辑,完成列表绑定与交互

首先补全你现有的locationText_Changed方法,将拿到的预测列表绑定到ListView上,再添加列表项点击的处理逻辑:

// 先定义一个全局的取消令牌源,用于后续防抖优化
private CancellationTokenSource _debounceCts;

private async void locationText_Changed(object sender, TextChangedEventArgs e)
{
    // 防抖逻辑:取消上一次未完成的请求
    _debounceCts?.Cancel();
    _debounceCts = new CancellationTokenSource();
    try
    {
        // 延迟300ms再发起请求,避免用户连续输入时频繁调用接口
        await Task.Delay(300, _debounceCts.Token);
        
        if (location == null)
        {
            await GetLocation();
        }
        string formattedLocation = string.Format("{0}%2C{1}", location.Latitude, location.Longitude);
        List<Prediction> predictionList = await VenueLogic1.GetVenues1(e.NewTextValue, formattedLocation);
        
        // 绑定预测列表到UI控件
        if (predictionList != null && predictionList.Any())
        {
            predictionListView.ItemsSource = predictionList;
            predictionListView.IsVisible = true;
        }
        else
        {
            predictionListView.IsVisible = false;
        }
    }
    catch (OperationCanceledException)
    {
        // 取消的请求无需处理
    }
}

// 预测列表项点击事件:选中后填充到输入框,隐藏列表
private void predictionListView_ItemTapped(object sender, ItemTappedEventArgs e)
{
    if (e.Item is Prediction selectedPrediction)
    {
        // 同样要和你Prediction类里的实际字段名对应
        locationEntry.Text = selectedPrediction.Description;
        predictionListView.IsVisible = false;
    }
    // 清空选中状态
    ((ListView)sender).SelectedItem = null;
}

注意事项

  • 如果你的Prediction类中用来展示地点的字段不是Description,需要把代码里所有绑定的Description替换为你实际的字段名
  • 300ms的延迟可以根据你的使用场景自行调整,平衡响应速度和接口请求频率
  • 如果需要更美观的展示效果,可以把ListView的ItemTemplate换成自定义的ViewCell,添加图标、次级地址等信息

内容的提问来源于stack exchange,提问作者Patrick89

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 16:06:03