Search code examples
c#maui

NET Maui - How do I populate a Picker manually in C# with a list of objects Without using MVC


I have a working Picker if I manually set the items in a loop using strings. And I am getting the OnChange and getting the string value with picker.Items[picker.SelectedIndex]

I have these objects.

<Picker x:Name="Event"
  Title="Select an Event"
  SelectedIndexChanged="OnEventIndexChanged">
</Picker>

public class Location
{
  public string LocationID { get; set; }
  public string LocationName { get; set; }
}

I have this working.

List<Location> L3 = DB.Table<Location>().ToList();
foreach (var L in L3)
  Event.Items.Add(L.LocationName);

What I need to do is have the picker use the List of Location objects to:

  1. Have the picker show Location.LocationNames
  2. OnSelect be able to retrieve the LocationID for the corrisponding SelectedName.

The docs for Picker say you can set it to an IList but I don't know how to convert from List To IList

I am not using MVC. Please do not give examples that use MVC in any way.


Solution

  • do this

    Event.ItemsSource = L3;
    Event.ItemDisplayBinding = new Binding("LocationName");
    

    to get the selected ID in SelectedIndexChanged

    var event = (Event)Event.ItemsSource[Event.SelectedIndex];
    var id = event.EventNumber;