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

Time:02-10

I have a list (List<Customer> l_Customer) that gets data from an API. <Customer> class includes fullname that is of string value. How can i get only the full names from that list and display them on the Picker's dropdown list?

CodePudding user response:

there is an example to do exactly this in the docs

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

or in code

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

CodePudding user response:

I make a simple example for your reference with MVVM.

Xaml:

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

Code behind:

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; }
}
  • Related