[英]Populate ListView when page is loaded (Xamarin.Forms) using a Command
我已嘗試在加載頁面時填充綁定到ObservableCollection的ListView失敗。 目前,我使用下面的代碼來處理按鈕(綁定到命令)。
視圖:
<Button Text="Load Items" Command="{Binding LoadItemsCommand}"></Button>
<ActivityIndicator IsRunning="{Binding IsBusy}" IsVisible="{Binding IsBusy}" />
<ScrollView>
<ListView ItemsSource="{Binding Items}">
.....
</ListView>
</ScrollView>
View.cs:
private ItemsViewModel _itemsViewModel;
public ItemsView()
{
InitializeComponent();
_itemsViewModel = new ItemsViewModel();
BindingContext = _itemsViewModel;
}
視圖模型:
public ObservableCollection<Item> Items{ get; set; }
public Command LoadItemsCommand { get; set; }
public ItemsViewModel()
{
Items = new ObservableCollection<Item>();
_isBusy = false;
LoadItemsCommand = new Command(async () => await LoadItems(), () => !IsBusy);
}
public async Task LoadItems()
{
if (!IsBusy)
{
IsBusy = true;
await Task.Delay(3000);
var loadedItems = ItemsService.LoadItemsDirectory();
foreach (var item in loadedItems)
Items.Add(item);
IsBusy = false;
}
}
這與按鈕完美配合,但我不知道如何自動執行。 我嘗試將listview的RefreshCommand屬性綁定到我的命令,但是什么也沒有。
有兩種方法,但是最好的方法是在視圖模型構造函數中啟動加載數據的任務。 我也不會將每個項目添加到可觀察的集合中,因為這將意味着最終添加UI更新。 加載完所有數據后,最好完全替換集合。
就像是:
public ItemsViewModel()
{
Items = new ObservableCollection<Item>();
_isBusy = false;
Task.Run(async () => await LoadItems());
}
public async Task LoadItems()
{
var items = new ObservableCollection<Item>(); // new collection
if (!IsBusy)
{
IsBusy = true;
await Task.Delay(3000);
var loadedItems = ItemsService.LoadItemsDirectory();
foreach (var item in loadedItems)
items.Add(item); // items are added to the new collection
Items = items; // swap the collection for the new one
RaisePropertyChanged(nameof(Items)); // raise a property change in whatever way is right for your VM
IsBusy = false;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.