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

How do I use a string to show Data in AutoSuggestBox in UWP

我正在尝试使用 AutoSuggestBox 来显示从字符串键入的数据。

我已经尝试制作一个包含一些单词的数组,这些单词将在用户键入时显示在 AutoSuggestBox 中,但是我需要来自 API 的数据,这些数据存储在一个字符串中以显示在 AutoSuggestBox 中.现在,我使用一个数组来显示用户键入的 3 个单词,以及包含 API 数据的字符串,这些数据被添加到 ListBox 中。

然而,这是在 AutoSuggestBox_TextChanged 方法中完成的,因此当用户键入时,我们获得的数据会添加到列表框中。

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 字符串中的数据在键入时被添加到列表框中。

I want the contents from the bottom arrow to show in the left arrow. So Bana Krisp Fruit Crackers Calories: 150 Protein to be showed in textbox where (Banana) is first arrow to the left.

根据您的要求,您可以使用 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;
}