Search code examples
.netxamlmaui.net-maui

How Do I Pass the Parent Object to ICommand from a Button in .NET Maui


In .NET Maui I have this XAML Page where I create a collection view from a heirarchy of Objects:

OpenJobGroup
    |
    |__List<OpenJob> OpenJobs
        |
        |__List<Position> Positions

<VerticalStackLayout>
    <CollectionView ItemsSource="{Binding OpenJobGroup.OpenJobs}">
        <CollectionView.ItemTemplate>
            <DataTemplate x:DataType="model:OpenJob">
                <Frame Margin="1,10" Padding="5">
                    <VerticalStackLayout>
                        <Frame">
                            <Grid>
                                ...
                                <Label Grid.Column="0" Grid.Row="0" Text="{Binding event_title}"/>
                            </Grid>
                        </Frame>

                        <Frame>
                            <ListView ItemsSource="{Binding positions}" SelectionMode="None">
                                <ListView.ItemTemplate>
                                    <DataTemplate x:DataType="model:Position">
                                        <ViewCell>
                                            <VerticalStackLayout>
                                                <HorizontalStackLayout>
                                                    <Label Text="{Binding position_title}"/>
                                                </HorizontalStackLayout>
                                                <Grid>
//Here is the Button....
//We are in the List<Position> Positions
//This List is in the OpenJob Object
//
//The Button is bound to an ICommand
//I need to send the ICommand the OpenJob Object

<Button Text="Note Availability" 
        CommandParameter="{Binding .}"
        Command="{Binding Source={RelativeSource AncestorType={x:Type viewmodel:OpenJobsDetailViewModel}}, Path=NoteAvailabilityCommand }"/>

                                                </Grid>
                                            ....
</VerticalStackLayout>

The ICommand is in my ViewModel but I don't know how to pass it the OpenJob object from the XAML

[ICommand]
async Task NoteAvailabilityAsync() {
    OpenJob openJob = "how to pass the object here?"
}

Solution

  • Based on this tutorial I came up with this markup which works:

    <Button Text="Note Availability" 
                CommandParameter="{Binding Source={RelativeSource AncestorType={x:Type model:OpenJob}}}" 
                Command="{Binding Source={RelativeSource AncestorType={x:Type viewmodel:OpenJobsDetailViewModel}}, 
                Path=NoteAvailabilityCommand }"/>