>Net Maui Binding Picker to List<Tuple<int, string>>

John Rutherford 21 Reputation points
2025-04-25T07:42:11+00:00

I have a ProjectSelectionPage to select an existing Project. The first part of the ViewModel is shown below.

The data that populates the is obtained via the ObservationService and returns Projects List<Tuple<int, string>>

public partial class ProjectSelectionPageViewModel : BaseViewModel
{
    private readonly ObservationService _observationService;

    public List<Tuple<int, string>>? Projects { get; private set; } = [];
    
    public int SelectedProjectIndex { get; set; } = -1;

    private bool isBusy;

    public ProjectSelectionPageViewModel(ObservationService observationService)
    {
        _observationService = observationService ?? throw new ArgumentNullException(nameof(observationService));
        Title = "Project Selection";
    }

I want to use the Projects List<Tuple<int, string>> to populate a picker control on the ContentPage shown below.

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="SunObs.Views.ProjectSelectionPage"
             xmlns:local ="clr-namespace:SunObs.Models"  
             xmlns:model ="clr-namespace:SunObs.Models"  
             xmlns:viewmodel="clr-namespace:SunObs.ViewModel"  
             x:DataType="viewmodel:ProjectSelectionPageViewModel"  
Title="{Binding Title}">
    <ScrollView>
    <VerticalStackLayout>
            <Grid RowDefinitions="Auto,Auto,Auto"
                  ColumnDefinitions="Auto,*"/>
            <Label Text="Start a New Project"
                   VerticalOptions="Center" 
                   HorizontalOptions="Center" />
            <Button Text="New Project" Grid.Column="1"
                Command="{Binding NewProjectCommand}"
                HorizontalOptions="Center" 
                VerticalOptions="Center" />
            <Label Text="Select Existing Project" Grid.Row="1" Grid.Column="0"
                   VerticalOptions="Center" 
                   HorizontalOptions="Center" />
            <Picker x:Name="ProjectPicker" Grid.Row="1" Grid.Column="1"
                    ItemsSource="{Binding Projects}"
                    SelectedIndex="{Binding SelectedProjectIndex}"/>

        </VerticalStackLayout>
    </ScrollView>
</ContentPage>

How do I set the ItemDisplayBinding to the string value of Project and make sure that the SelectedItem (int value of Projects) is captured by the SelectedIndex value?

TIA

XAML
XAML
A language based on Extensible Markup Language (XML) that enables developers to specify a hierarchy of objects with a set of properties and logic.
848 questions
0 comments No comments
{count} votes

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.