【发布时间】:2021-10-16 00:49:45
【问题描述】:
我正在尝试使用 Xamarin 表单创建应用程序,其中一个页面是 ListView。我需要将它绑定到 ObservableCollection,它从 Azure SQL 获取其值,但绑定失败。 Observable 集合确实是从 Web API 填充的,所以我不确定问题出在哪里。任何帮助表示赞赏!
xaml 页面:
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" xmlns:viewModel="clr-namespace:SiteVisits.ViewModels" xmlns:model="clr-namespace:SiteVisits.Models"
x:DataType="viewModel:AllWellsViewModel"
x:Class="SiteVisits.Views.AllWells">
<ListView x:Name="WellsCollection"
ItemsSource="{Binding WellsCollection}"
HasUnevenRows="True">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<StackLayout Padding="10" x:DataType="model:Well">
<Label Text="{Binding Description}"
FontSize="Large"
VerticalOptions="Center"/>
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</ContentPage>
xaml.cs:
public partial class AllWells : ContentPage
{
AllWellsViewModel viewModel;
public AllWells(AllWellsViewModel viewModel)
{
InitializeComponent();
this.viewModel = viewModel;
BindingContext = this.viewModel;
}
public AllWells()
{
InitializeComponent();
viewModel = new AllWellsViewModel();
BindingContext = viewModel;
}
}
视图模型:
public class AllWellsViewModel : BaseViewModel
{
public ObservableCollection<Well> WellsCollection { get; set; }
public AllWellsViewModel()
{
Title = "Browse";
WellsCollection = new ObservableCollection<Well>();
InitializeData();
}
async void InitializeData()
{
var wellDataStore = new WellDataStore();
var wells = await wellDataStore.GetAllWells();
if (wells != null)
{
WellsCollection = new ObservableCollection<Well>(wells);
}
}
}
型号:
public class Well
{
[PrimaryKey, AutoIncrement]
public int Id { get; set; }
public string Description { get; set; }
}
【问题讨论】:
-
您正在初始化
WellsCollection两次,并且您正在从构造函数调用异步方法
标签: listview xamarin.forms data-binding