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

3pvhb19x  于 2022-12-07  发布在  其他
关注(0)|答案(2)|浏览(84)

我有一个从API获取数据的列表(List<Customer> l_Customer)。<Customer>类包括字符串值的fullname。如何从该列表中只获取全名并将其显示在选取器的下拉列表中?

wi3ka0sx

wi3ka0sx1#

我用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; }
}
xmd2e60i

xmd2e60i2#

在文档中有一个例子可以做到这一点

<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");

相关问题