Search code examples
mauimaui-community-toolkit

.NET MAUI Databind Picker to Dictionary Values


I am using .NET MAUI with MAUI Essentials to try and connect a Picker to a dictionary of months with their corresponding key representing their numerical month. I would like for the dictionary's string value to populate the drop-down list (Picker). Upon selecting a month, the numerical key should update "SelectedDictOfMonths" for consumption later in the ViewModel.

XAML ATTEMPT #1:

<Picker
ItemsSource="{Binding DictOfMonths}"
SelectedItem="{Binding SelectedDictOfMonths}"/>

XAML ATTEMPT #2:

<Picker
ItemsSource="{Binding DictOfMonths}"
SelectedItem="{Binding SelectedDictOfMonths}"
ItemDisplayBinding="{Binding DictOfMonths.Values}"/>

C# VIEWMODEL:

[ObservableProperty]
Dictionary<int, string> dictOfMonths = new Dictionary<int, string>()
{
    { 1, "January" },
    { 2, "February" },
    { 3, "March" },
    { 4, "April" },
    { 5, "May" },
    { 6, "June" },
    { 7, "July" },
    { 8, "August" },
    { 9, "September" },
    { 10, "October" },
    { 11, "November" },
    { 12, "December" },
};

[ObservableProperty]
int selectedDictOfMonths = 0;

Sorry if this is a simple question. I've searched the Microsoft documentation, used common sense, asked AI, and otherwise tried to piece together other people's answers, but still fail to make the connection. Thanks in advance!


Solution

  • A Picker can be populated with data by setting its ItemsSource property to an IList collection.

    Set the ItemsSource property

    That means the ItemsSource property should be set to a IList Collection and a Dictionary is not.

    So there are many choices for your case. Here is just an example:

    [ObservableProperty]
    public IList<KeyValuePair<int, string>> listOfMonths = new List<KeyValuePair<int, string>> {
    new KeyValuePair<int, string>(1, "January"),
    new KeyValuePair<int, string>(2, "February"),
    ...
    
    };
    

    And in xaml,

    <Picker
        ItemsSource="{Binding ListOfMonths}"
        SelectedItem="{Binding SelectedListOfMonths}"
        ItemDisplayBinding="{Binding Value}"/>
    

    In this way, the selectedListOfMonths should be type KeyValuePair<int, string>

    [ObservableProperty]
    KeyValuePair<int, string> selectedListOfMonths;
    

    You could use SelectedListOfMonths.Key to get the numeric value.

    And if you still want to use type int for selectedListOfMonths, you could try use a Binding value converters

    Hope it helps!