我正在尝试将Observable对象集合绑定到列表视图。 我在视图模型中放了一个调试,它显示集合在那里。但它似乎并没有显示在前端。
这是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 :(得分:1)
在DriverDashboardViewModel.GetLabelInfo()
方法中,您要将结果分配给_routelabels
。但是_routelabels
并没有调用OnPropertyChanged()
,这是更改要求用户重新评估其绑定所必需的。{/ p>
我建议将await service.return_label_info();
的结果直接分配给routeLabels
。
但您也可以按照现在的方式保留GetLabelInfo()
代码,只需在_routelabels
分配后添加以下内容即可手动触发UI更新:OnPropertyChanged(nameof(routeLabels));
总而言之,请做以下两件事之一:
public async Task GetLabelInfo() {
routeLabels = await service.return_label_info();
}
或者:
public async Task GetLabelInfo() {
_routelabels = await service.return_label_info();
OnPropertyChanged(nameof(routeLabels));
}