2016-11-29 113 views
0

我試圖在加載頁面時填充綁定到ObservableCollection的ListView失敗。目前我使用下面的代碼使用按鈕(綁定到Command)。當使用命令加載頁面(Xamarin.Forms)時填充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屬性綁定到我的命令,但沒有任何結果。

回答

3

有幾種方法,但最好的方法是啓動加載數據的視圖模型構造函數中的任務。我也不會將每個項目添加到可觀察集合中,因爲這將意味着添加結束時的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; 
    } 
} 
+0

感謝您的幫助@JimBobBennet。它通過開啓視圖模型的構造函數來完成任務。然而,集合的交換不起作用,它只有在我直接在循環中將項目添加到公共Items屬性時才起作用。此外,我的印象是,沒有必要調用ObservableCollections上的PropertyChanged。在我的情況下,它沒有這條線 –

+0

如果你添加到現有的集合,那麼UI將更新,但它會很慢,因爲UI會重新繪製你添加的每個項目。對於1,000件商品,你將會遇到不好的時間。 屬性更改是因爲在我的示例中,它將全新集合替換爲「Items」屬性的值,因此您需要提高屬性更改以告訴它重新加載新集合 - 導致1 UI更新 – JimBobBennett

+0

Got它!感謝您的澄清@JimBobBennett –

相關問題