首页 > 解决方案 > Xamarin Forms - 刷新 ListView 时连接到远程数据库

问题描述

我正在做一个预订应用程序,当用户刷新 ListView 时,它应该连接到远程数据库以获取所有预订并更新 ListView。

我的onAppearing方法中有代码

我尝试将以下代码添加到刷新绑定中,但没有成功:

       ItemsPage ip = new ItemsPage();
       ArrayList reservations = new ArrayList();
       reservations =  await ip.CheckReservations(ItemsPage.currentDate);
       ItemsPage.reservations = reservations;

OnAppearing()void中连接数据库的代码

protected async override void OnAppearing()
    {
        base.OnAppearing();
        reservations = new ArrayList();
        reservations = await CheckReservations(currentDate);
    }

刷新绑定:

      public class ItemsViewModel : BaseViewModel
{
    public ObservableCollection<Termin> Items { get; set; }
    public Command LoadItemsCommand { get; set; }

    public ItemsViewModel()
    {
        Title = "Rezervácie";
        Items = new ObservableCollection<Termin>();
        LoadItemsCommand = new Command(async () => await ExecuteLoadItemsCommand());
    } 

    async Task ExecuteLoadItemsCommand()
    {

        if (IsBusy)
            return;

        IsBusy = true;
        try
        {

            var items = await DataStore.GetItemsAsync(true);
            foreach (var item in items)
            {

                Items.Add(item);

            }
        }
        catch (Exception ex)
        {
            Debug.WriteLine(ex);
        }
        finally
        {
            IsBusy = false;
        }


    }
}}

GetItemsAsync:

    public async Task<IEnumerable<Termin>> GetItemsAsync(bool forceRefresh = false)
    {
        return await Task.FromResult(items);
    }

ItemsPage 是我的观点。

在我的 viewModel 中调用了 refresh 方法。导航到另一个页面并刷新作品。

预订后我打电话给:

 ItemsListView.BeginRefresh();

这确实有效,但是从刷新命令中引用该行会使 LV 不填充。

XAML 代码:

   <ListView x:Name="ItemsListView"
            ItemsSource="{Binding Items}"
            VerticalOptions="FillAndExpand"
            HasUnevenRows="true"
            BackgroundColor="DarkGreen" 
            SeparatorColor="Black"
            RefreshCommand="{Binding LoadItemsCommand}"
            IsPullToRefreshEnabled="true"
            IsRefreshing="{Binding IsBusy, Mode=OneWay}"
            CachingStrategy="RecycleElement"
            ItemSelected="OnItemSelected">

标签: listviewxamarinxamarin.forms

解决方案


ViewModel 中的对象列表应该是 ObservableCollection,以便列表检测到列表中的更改并相应地更新 UI。

在您的模型中:

 public ObservableCollection<YourModel> ListViewItems { get; set; }

在 XAML 中

 <ListView ItemsSource="{Binding ListViewItems}" />

推荐阅读