如何在UWP中使用字符串在AutoSuggestBox中显示数据

时间:2019-04-28 00:18:49

标签: c# api uwp suggestbox

我正在尝试使用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向我显示键入的字符串中的数据。例如,“香蕉”-弹出带有香蕉名称的食物清单。

enter image description here

但是实际结果是AutoSuggestBox,显示了键入时将ArrayData和API字符串形式的字符串添加到ListBox中的情况。

1 个答案:

答案 0 :(得分:0)

  

我希望底部箭头中的内容显示在左侧箭头中。因此Bana Krisp水果饼干的卡路里: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;
}