【问题标题】:Dynamically create ListView rows from SQL Lite DB从 SQLite DB 动态创建 ListView 行
【发布时间】:2021-05-01 12:10:40
【问题描述】:

我希望创建一个应用程序,从而根据 SQL 数据库条目自动创建 ListView 行 - 最多 5 个 ListView 行。

人物类:

using SQLite;

namespace AppPeople
{
    public class Person
    {
        [PrimaryKey, AutoIncrement]
        public int ID { get; set; }
        public string Name { get; set; }
        public int Age { get; set; }
    }
}

数据库.cs:

using System.Collections.Generic;
using System.Threading.Tasks;
using SQLite;

namespace AppPeople
{
    public class Database
    {
        readonly SQLiteAsyncConnection _database;

        public Database(string dbPath)
        {
            _database = new SQLiteAsyncConnection(dbPath);
            _database.CreateTableAsync<Person>().Wait();
        }

        public Task<List<Person>> GetPeopleAsync()
        {
            return _database.Table<Person>().ToListAsync();
        }

        public Task<int> SavePersonAsync(Person person)
        {
            return _database.InsertAsync(person);
        }
    }
}

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" x:Class="AppPeople.MainPage">
    <ListView x:Name="saved_properties_list">
        <ListView.ItemTemplate>
            <DataTemplate>
                <ViewCell>
                    <StackLayout Orientation="Horizontal" 
                        HorizontalOptions="FillAndExpand"
                        Margin="20, 10, 20, 0" >
                        <Label Text="{Binding Name}" HorizontalOptions="StartAndExpand" />
                        <Label Text="{Binding Age}" />
                    </StackLayout>
                </ViewCell>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>
</ContentPage>

MainPage.cs:

        protected override async void OnAppearing()
        {
            base.OnAppearing();
            saved_properties_list.ItemsSource = await MainPage.Database.GetPropertiesAsync();
        }


public Task> GetPropertiesAsync()
{
    return database.Table().ToListAsync();
}

我将如何进行更改,以便根据最多包含 5 个 ListView 行的 SQL DB 条目自动创建 ListView 行?谢谢。

【问题讨论】:

    标签: c# sqlite listview xamarin


    【解决方案1】:

    使用 LINQ Take 限制结果数

    return _database.Table<Person>().Take(5).ToListAsync();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-12-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-04
      • 2013-08-28
      • 2017-02-25
      • 2011-07-03
      相关资源
      最近更新 更多