2017-06-22 98 views
1

我想將Observable Collection對象綁定到列表視圖。 我已經在視圖模型中進行了調試,它顯示集合在那裏。但它似乎並沒有在前端展示。綁定到ListView Xamarin Froms

這是XAML中:

<StackLayout>  



    <ListView 
       x:Name="dataList"      
       ItemsSource="{Binding routeLabels}" > 

     <ListView.ItemTemplate> 
      <DataTemplate> 
       <TextCell Text="{Binding RouteName}"/> 
      </DataTemplate> 

     </ListView.ItemTemplate> 

    </ListView> 

</StackLayout> 

背後的代碼:

public partial class DriverDashboardView : ContentPage 
{ 
    private DriverDashboardViewModel driverdashboardviewmodel; 


    public DriverDashboardView() 
    { 

     InitializeComponent(); 

     this.Title = "Driver's Dashboard"; 
     BindingContext = driverdashboardviewmodel = new DriverDashboardViewModel(); 

    } 

    protected async override void OnAppearing() 
    { 
     base.OnAppearing(); 
     await driverdashboardviewmodel.GetLabelInfo(); 
    } 

} 

和視圖模型:

public class DriverDashboardViewModel:BaseViewModel,INotifyPropertyChanged 
{ 


    public DriverDashboardViewModel() 
    { 


    } 

    public async Task GetLabelInfo() 
    { 
     _routelabels = await service.return_label_info(); 

    } 

    // property change handler to bind to UI 
    private ObservableCollection<RouteInfo> _routelabels; 
    public ObservableCollection<RouteInfo> routeLabels 
    { 
     get { return _routelabels; } 
     set 
     { 
      if (Equals(value, _routelabels)) return; 
      _routelabels = value; 
      OnPropertyChanged(nameof(routeLabels)); 
     } 
    } 

    public event PropertyChangedEventHandler PropertyChanged; 
    protected void OnPropertyChanged(string propertyName) 
    { 
     if (PropertyChanged != null) 
      PropertyChanged(this, 
       new PropertyChangedEventArgs(propertyName)); 
    } 
} 

而且RouteInfo類:

public class RouteInfo 
{ 
    public string RouteName { get; set; } 
    public int Stops { get; set; } 
    public string DayOf { get; set; } 

} 

正如我所說,我把調試視圖模型,我可以看到數據在那裏。 但我不能在前端看到它。

任何想法?

+0

如果您刪除'ItemTemplate'你看到在你面前的條目正確數量-結束?如果是這樣,那麼你的模板是一個問題。如果沒有,那麼這聽起來像是一個綁定問題。 – Mashton

回答

1

在您的DriverDashboardViewModel.GetLabelInfo()方法中,您將結果分配給_routelabels。但是_routelabels不會調用OnPropertyChanged(),這是更改所需的,以告知UI重新評估其綁定。

我建議將await service.return_label_info();的結果直接分配給routeLabels

但你也可以保持GetLabelInfo()代碼,現在是這樣的,只是添加以下後_routelabels分配手動跳跳虎一個UI更新:OnPropertyChanged(nameof(routeLabels));

因此,在總結做的這2兩件事:

public async Task GetLabelInfo() { 
    routeLabels = await service.return_label_info(); 
} 

或者:

public async Task GetLabelInfo() { 
    _routelabels = await service.return_label_info(); 
    OnPropertyChanged(nameof(routeLabels)); 
} 
+0

工作正常!謝謝! 我會接受這個,當它讓我。 – user3355961