2016-11-29 112 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 –

相关问题