public static ObservableCollection <FoodSearch> Result(List <Food> foods) { var result = new FoodSearch(); var collection = new ObservableCollection <FoodSearch>(); foreach (Food f in foods) { result = new FoodSearch() { Name = f.Name, Id = f.Id }; collection.Add(result); } return(collection); }
public MainPage() { InitializeComponent(); foods = new List <Food>(); foodCollection = new ObservableCollection <FoodSearch>(); infoLabel.Margin = new Thickness(10, 50, 0, 0); var layout = new StackLayout { VerticalOptions = LayoutOptions.StartAndExpand, Children = { new Label { HorizontalTextAlignment = TextAlignment.Center, VerticalTextAlignment = TextAlignment.Center, Text = "Sök näringsinnehåll", FontSize = Device.GetNamedSize(NamedSize.Large, typeof(Label)), FontAttributes = FontAttributes.Bold, TextColor = Color.OrangeRed, Margin = new Thickness(10) } } }; Content = layout; var search = new StackLayout { Orientation = StackOrientation.Horizontal }; var searchEntry = new Entry { HorizontalTextAlignment = TextAlignment.Start, HorizontalOptions = LayoutOptions.FillAndExpand }; Button searchButton = new Button { Text = "Sök", HorizontalOptions = LayoutOptions.End }; search.Children.Add(searchEntry); search.Children.Add(searchButton); layout.Children.Add(search); list.ItemsSource = foodCollection; searchButton.Clicked += async(s, e) => { layout.Children.Add(list); layout.Children.Remove(table); layout.Children.Remove(infoLabel); list.ItemsSource = null; foods = await GetMatchingFoods(searchEntry.Text); if (foods.Count == 0) { layout.Children.Remove(list); infoLabel.Text = "Din sökning gav inga träffar"; layout.Children.Add(infoLabel); } foodCollection = FoodSearch.Result(foods); list.ItemsSource = foodCollection; }; infoLabel.Text = ""; infoLabel.FontSize = Device.GetNamedSize(NamedSize.Medium, typeof(Label)); infoLabel.FontAttributes = FontAttributes.Bold; infoLabel.TextColor = Color.OrangeRed; list.ItemSelected += async(s, e) => { list.ItemsSource = null; layout.Children.Remove(list); searchEntry.Text = ""; var selectedFood = (FoodSearch)e.SelectedItem; var food = await GetFoodById(selectedFood.Id); infoLabel.Text = food.Name; Energy.Text = food.EnergyInKcal.ToString(); Carbohydrates.Text = food.Carbohydrates.ToString(); Fat.Text = food.Fat.ToString(); Protein.Text = food.Protein.ToString(); Fiber.Text = food.Fibers.ToString(); Sugars.Text = food.Sugars.ToString(); SaturatedFat.Text = food.SaturatedFat.ToString(); Salt.Text = food.Salt.ToString(); VitD.Text = food.VitaminD.ToString(); Iron.Text = food.Iron.ToString(); layout.Children.Add(infoLabel); layout.Children.Add(table); }; }