c# - 如何使用字符串在 UWP 的 AutoSuggestBox 中显示数据
问题描述
我正在尝试使用 AutoSuggestBox 将数据显示为从字符串中键入。
我尝试使用一些单词创建一个数组,这些单词将在用户键入时显示在 AutoSuggestBox 中,但是我需要来自 API 的数据,该数据存储在字符串中以显示在 AutoSuggestBox 中。现在,我使用一个数组来显示用户键入的 3 个单词,并将包含 API 数据的字符串添加到 ListBox 中。
然而,这是在 AutoSuggestBox_TextChanged 方法中完成的,因此当用户键入时,我们获得的数据会被添加到 ListBox。
private async void AutoSuggestBox_TextChanged(AutoSuggestBox sender, AutoSuggestBoxTextChangedEventArgs args)
{
string[] Autoitems = new string[] { "check", "apple", "banana" } //Temporary Array for AutoSuggestBox
var Auto = (AutoSuggestBox)sender;
var Suggestion = Autoitems.Where(p => p.StartsWith(Auto.Text, StringComparison.OrdinalIgnoreCase)).ToArray();
Auto.ItemsSource = Suggestion; //This displays only items from array as being typed.
string searchedName = SearchBox.Text;
myFood = await NutritionixAPI.GetFood(searchedName);
//The data I get from the API is stored in the temp string
string temp = myFood.hits[0].fields.item_name + " Calories: " + myFood.hits[0].fields.nf_calories + " Protein: " + myFood.hits[0].fields.nf_protein + " Fat: " + myFood.hits[0].fields.nf_total_fat;
ResultListBox.Items.Add(temp); //temp string data is added to a listbox
Total += myFood.hits[0].fields.nf_calories;
TotalCalories.Text = ((int)Total).ToString(); //Adds the calories of each added food to the Total Variable and Display it
}
我希望 AutoSuggestBox 向我显示正在输入的字符串中的数据。例如“Bana” - 弹出名称为 Bana 的食物列表。
但实际结果是 AutoSuggestBox 显示 ArrayData 和字符串中的 API 数据被添加到 ListBox 中。
解决方案
我希望底部箭头的内容显示在左箭头中。所以 Bana Krisp Fruit Crackers 卡路里:150 蛋白质将显示在文本框中,其中 (Banana) 是左侧的第一个箭头。
根据您的要求,您可以获取键入的数据,NutritionixAPI
然后将数据转换为格式字符串。为存储格式字符串的 AutoSuggestBox Itemsource 创建一个新列表。
private async void AutoSuggestBox_TextChanged(AutoSuggestBox sender, AutoSuggestBoxTextChangedEventArgs args)
{
switch (args.Reason)
{
case AutoSuggestionBoxTextChangeReason.ProgrammaticChange:
case AutoSuggestionBoxTextChangeReason.SuggestionChosen:
sender.ItemsSource = null;
return;
}
var query = sender.Text;
var hits = await NutritionixAPI.GetFoods(query);
List<string> items = new List<string>();
foreach (var hit in hits)
{
string temp = hit.fields.item_name + " Calories: " + hit.fields.nf_serving_size_qty + " Protein: " + hit.fields.nf_serving_size_unit + " Fat: " + hit.fields.item_id;
if (items.Exists(p => p == temp) == false)
{
items.Add(temp);
}
}
var Suggestion = items.Where(p => p.StartsWith(sender.Text, StringComparison.OrdinalIgnoreCase)).ToArray();
sender.ItemsSource = Suggestion;
}
推荐阅读
- arrays - 将数组传递给子或函数时 ByRef 参数类型不匹配
- wordpress - 此服务器上未启用 HTTP 环回连接 - docker 上的 wordpress
- linux - Filebeat 和 Logstash 有时会读取旧文件
- angular - Angular 7 Http获取请求功能退出?
- jquery - Slick Slider 自定义 HTML 分页
- r - 即使在使用 rm.na = TRUE 时,NA 值也会导致 summarise() 出现问题
- jquery - jQuery 数据表不显示标题
- matlab - Graphviz 和 Matlab - 'dot' 不被识别为内部或外部命令
- vb.net - VBnet 访问字节的各个位 // BitArray 长度和计数等于字节值?
- sql - 在mssql中加入四个表