如何将数据从 List<class> 绑定到 Xamarin 中的 Picker 元素

How to bind data from a List<class> to Picker element in Xamarin

我有一个从 API 获取数据的列表 (List<Customer> l_Customer)。 <Customer> class 包含字符串值的 fullname 。我怎样才能只从该列表中获取全名并将它们显示在选择器的下拉列表中?

文档中有 example 可以做到这一点

<Picker Title="Select a customer"
    ItemsSource="{Binding l_Customer}"
    ItemDisplayBinding="{Binding fullname}" />

或在代码中

var picker = new Picker { Title = "Select a Customer" };
picker.SetBinding(Picker.ItemsSourceProperty, "l_Customer");
picker.ItemDisplayBinding = new Binding("fullname");

我用MVVM做了一个简单的例子供大家参考。

Xaml:

  <Picker ItemsSource="{Binding l_Customer}" ItemDisplayBinding="{Binding fullname}"></Picker>

后面的代码:

public partial class Page14 : ContentPage
{
    public Page14()
    {
        InitializeComponent();
        this.BindingContext = new CustomerViewModel();
    }
}
public class CustomerViewModel
{
    public List<Customer> l_Customer { get; set; }
    public CustomerViewModel()
    {
        l_Customer = new List<Customer>()
        {
            new Customer(){ fullname="A"},
            new Customer(){ fullname="B"},
            new Customer(){ fullname="C"},
        };
    }
}
public class Customer
{
    public string fullname { get; set; }
}