Error while displaying in the list
I have an error at the time of showing in the view the query to the api is generated correctly but at the time of listing they are not shown in the view. As it appears in the screenshot, it does not show any results.
Vista `
<ContentPage.BindingContext>
<ViewModels:ComidaViewModel>
</ViewModels:ComidaViewModel>
</ContentPage.BindingContext>
<StackLayout>
<SearchBar Placeholder="Busca tu alimento por categoria"
x:Name="search"
SearchCommand="{Binding SearchCommand}"
SearchCommandParameter="{Binding Text, Source={x:Reference search}}"></SearchBar>
<ListView
ItemsSource="{Binding Items}"
RowHeight="250">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<Frame CornerRadius="5"
Margin="5"
BackgroundColor="Red">
<StackLayout>
<Image Source="{Binding urlImg}" HeightRequest="100"></Image>
<Label Text="{Binding nombreAlimento}"></Label>
</StackLayout>
</Frame>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</StackLayout>
**View Model**
ApiRest apiRest = new ApiRest();
public ObservableCollection<ComidaModel> Items { get; set; }
public string categoriaAlimento { get; set; }
public ICommand SearchCommand { get; set; }
public ComidaViewModel()
{
try
{
SearchCommand =
new Command(async (text) =>
{
try
{
string response = "";
Task.Run(async () =>
{
response = await apiRest.ConsultaAlimentos(text.ToString());
}).Wait();
List<ComidaModel> consulta = JsonConvert.DeserializeObject<List<ComidaModel>>(response);
Items = new ObservableCollection<ComidaModel>();
foreach (ComidaModel consultas in consulta)
{
Items.Add(consultas);
}
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
});
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
}
`
1条答案
按热度按时间txu3uszq1#
From the code you posted, I found you didn't define any view in the
ViewCell
of theListView
and bind the relative property of modelComidaModel
of datasourceItems
.You can refer to the following code:
For more information, you can check document: https://learn.microsoft.com/en-us/xamarin/xamarin-forms/user-interface/listview/customizing-cell-appearance .
Update 1:
Follow the same error does not show any results does not show the list
For the problem, please try to initialize variable
Items
in the constructor of viewmodelComidaViewModel
instead of initializing in theSearchCommand
.Please refer to the following code:
Update 2
Based on your code, I created a demo and simulated this function. I added several functions:
1.add the Initial data
2.add the filter function
GetSearchResults
You can refer to the following code:
ComidaViewModel.cs
ComidaModel.cs
MainPage.xaml