Xamarin Listview中的搜索筛选器未在视图中显示

qlckcl4x  于 2022-12-07  发布在  其他
关注(0)|答案(1)|浏览(141)

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);
            }

        }

    }

`

I expected the list to be displayed with the filter

txu3uszq

txu3uszq1#

From the code you posted, I found you didn't define any view in the ViewCell of the ListView and bind the relative property of model ComidaModel of datasource Items .

Items = new ObservableCollection<ComidaModel>();

You can refer to the following code:

<ListView  x:Name="lstView" RowHeight="60">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <ViewCell>
        <!--  add your control here and bind the property of your item ComidaModel  -->
                        <StackLayout Orientation="Horizontal" HorizontalOptions="Fill" BackgroundColor="Olive">
                            <StackLayout Orientation="Vertical">
                                <Label Text = "{Binding Name}" FontSize="24" AbsoluteLayout.LayoutBounds="0.25, 0.25, 400, 40"/>
                                <Label Text = "{Binding Type}" AbsoluteLayout.LayoutBounds="50, 35, 200, 25"/>
                            </StackLayout>
                            <Image Source="{Binding Image}" HorizontalOptions="End" AbsoluteLayout.LayoutBounds="250.25, 0.25, 50, 50 "/>
                        </StackLayout>
                    </ViewCell>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>

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 viewmodel ComidaViewModel instead of initializing in the SearchCommand .
Please refer to the following code:

public ComidaViewModel() 
        {
            consulta = new List<ComidaModel>();

            //initialize variable  `Items ` here 
            Items = new ObservableCollection<ComidaModel>();

            try
            {
                SearchCommand =
               new Command(async (text) =>
               {
                   try
                   {
                       // other code

                       // remove code here
                       //Items = new ObservableCollection<ComidaModel>();
                       foreach (ComidaModel consultas in consulta)
                       {
                           Items.Add(consultas);
                       }
                   }
                   catch (Exception ex)
                   {
                       Console.WriteLine(ex);
                   }

               });
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }

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

public class ComidaViewModel 
{
    public ObservableCollection<ComidaModel> Items { get; set; }

    public List<ComidaModel> consulta { get; set; }
    public string categoriaAlimento { get; set; }

    public ICommand SearchCommand { get; set; }

    public  List<ComidaModel> GetSearchResults(string queryString)
    {
        var normalizedQuery = queryString?.ToLower() ?? "";
        return consulta.Where(f => f.nombreAlimento.ToLowerInvariant().Contains(normalizedQuery)).ToList();
    }

    public ComidaViewModel()
    {
        consulta = new List<ComidaModel>();

        //  you can init data here
        consulta.Add(new ComidaModel { urlImg = "cherry.png", nombreAlimento = "test1" });
        consulta.Add(new ComidaModel { urlImg = "grass.png", nombreAlimento = "abc2" });
        consulta.Add(new ComidaModel { urlImg = "cherry.png", nombreAlimento = "abd3" });
        consulta.Add(new ComidaModel { urlImg = "grass.png", nombreAlimento = "def4" });
        consulta.Add(new ComidaModel { urlImg = "cherry.png", nombreAlimento = "fgh5" });
        consulta.Add(new ComidaModel { urlImg = "grass.png", nombreAlimento = "jkl6" });
        consulta.Add(new ComidaModel { urlImg = "cherry.png", nombreAlimento = "test7" });

        Items = new ObservableCollection<ComidaModel>(consulta);

        //Items = new ObservableCollection<ComidaModel>();

        try
        {
            SearchCommand =
           new Command<string>(async (text) =>
           {
               try
               {
                   List<ComidaModel> data = new List<ComidaModel>();

                   data = GetSearchResults(text);

                   Items.Clear();
                   foreach (ComidaModel model in data)
                   {
                       Items.Add(model);
                   }

               }
               catch (Exception ex)
               {
                   Console.WriteLine(ex);
               }
           });
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex);
        }
    }
}

ComidaModel.cs

public class ComidaModel 
{
    public string urlImg { get; set; }
    public string nombreAlimento { get; set; }
}

MainPage.xaml

<?xml version="1.0" encoding="utf-8" ?> 
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" 
             xmlns:formlistviewapp="clr-namespace:FormListViewApp"
             x:Class="FormListViewApp.MainPage">

    <ContentPage.BindingContext>
        <formlistviewapp:ComidaViewModel></formlistviewapp:ComidaViewModel>
    </ContentPage.BindingContext>

    <StackLayout>
        <SearchBar Placeholder=""
                   x:Name="search"
                   SearchCommand="{Binding SearchCommand}"
                   SearchCommandParameter="{Binding Text, Source={x:Reference search}}"></SearchBar>
        <ListView
            ItemsSource="{Binding Items}"
            RowHeight="100">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <ViewCell>
                        <Frame CornerRadius="5"
                               Margin="5"
                               BackgroundColor="Yellow">
                            <StackLayout Orientation="Horizontal">
                                <Image Source="{Binding urlImg}" HeightRequest="30"></Image>
                                <Label Text="{Binding nombreAlimento}"></Label>
                            </StackLayout>
                        </Frame>
                    </ViewCell>
                </DataTemplate>
            </ListView.ItemTemplate>

        </ListView>
    </StackLayout>

</ContentPage>

相关问题