xamarin.forms listview 由 BindingContext 和 viewmodel 填充



我是Xamarin的新手,但我来自C#背景。

我正在尝试通过将视图模型传递给绑定上下文属性来设置列表视图的项目源。我知道我可以在后面的代码中以编程方式设置 itemssoruce,但我认为通过绑定上下文设置它是正确的方法,如果我错了,请纠正我。

让我从我目前拥有的情况开始。

这是我拥有的视图模型:

public class AirportSelectVM
{
public int AirportID { get; set; }
public string AirportICAO { get; set; }
public int VolumeGallons { get; set; }
}

在后面的代码中,我正在这样做:

private void SetInitialListView()
{
ObservableCollection<AirportSelectVM> listAirport = new ObservableCollection<AirportSelectVM>();
AirportSelectVM firstAirport = new AirportSelectVM();
listAirport.Add(firstAirport);
BindingContext = listAirport;
}

在 XAML 中,我有:

<ContentPage.Content>
<StackLayout>
<Picker x:Name="pickerAircraft" ItemDisplayBinding="{Binding TailNumber}" SelectedItem="{Binding Id}" SelectedIndexChanged="PickerAircraft_SelectedIndexChanged" Title="Aircraft Selector"></Picker>
<ListView ItemsSource="{Binding listAirport}">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<StackLayout Padding="10,10,10,10">
<Label Text="Leg 1 Arrival" />
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</StackLayout>
</ContentPage.Content>

只是为了比较,选取器项源是在后面的代码中设置的,但最终我也想在绑定上下文中移动它。

因此,我的主要问题是如何通过绑定上下文设置列表视图的项目源?

您将PageBindingContext设置为listAirport。 因此,ItemsSource 将与页面绑定相同

<ListView ItemsSource="{Binding .}">

如果你想以"正确的方式"做到这一点,你应该了解更多关于 MVVM 模式的信息。 对于每个页面,您都绑定了一个页面视图模型,该模型将成为模型(数据(和 UI 之间的桥梁。

https://learn.microsoft.com/en-us/xamarin/xamarin-forms/xaml/xaml-basics/data-bindings-to-mvvm

现在,如果您只想拥有一个工作代码,则需要像这样直接设置ItemsSource

<ContentPage.Content>
<StackLayout>
<Picker x:Name="pickerAircraft" ItemDisplayBinding="{Binding TailNumber}" SelectedItem="{Binding Id}" SelectedIndexChanged="PickerAircraft_SelectedIndexChanged" Title="Aircraft Selector"></Picker>
<ListView x:Name="AirportListView">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<StackLayout Padding="10,10,10,10">
<Label Text="Leg 1 Arrival" />
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</StackLayout>
</ContentPage.Content>

代码隐藏:

private void SetInitialListView()
{
ObservableCollection<AirportSelectVM> listAirport = new ObservableCollection<AirportSelectVM>();
AirportSelectVM firstAirport = new AirportSelectVM();
listAirport.Add(firstAirport);
AirportListView.ItemsSource = listAirport;
}

最新更新