sinsedrix
sinsedrix

Reputation: 4775

Binding a command to a parent view model in MAUI

I'd like to reference a parent viewmodel as a command binding. I was expecting the MAUI syntax would work like the Xamarin does but I get the following errors:

Here is the syntax I tried:

    <ContentPage ... x:Class="ParentPage" x:DataType="ParentViewModel" x:Name="Parent">
        <StackLayout>
            <ListView ItemsSource="{Binding Tabs}">
                <ListView.ItemTemplate>
                    <DataTemplate x:DataType="TabViewModel">
                        <ViewCell>
                            <Button Text="Do it"
                                Command="{Binding Path=SelectTab
                                    RelativeSource={RelativeSource AncestorType={x:Type ParentPage}}}" />
                        </ViewCell>
                    </DataTemplate>
                </ListView.ItemTemplate>
            </ListView>
        </StackLayout>
    </ContentPage>



Or:
    <ContentPage ... x:Class="ParentPage" x:DataType="ParentViewModel" x:Name="Parent">
        <StackLayout>
            <ListView ItemsSource="{Binding Tabs}">
                <ListView.ItemTemplate>
                    <DataTemplate x:DataType="TabViewModel">
                        <ViewCell>
                            <Button Text="Do it"
                                Command="{Binding Path=SelectTab
                                    Source={x:Reference Parent}}" />
                        </ViewCell>
                    </DataTemplate>
                </ListView.ItemTemplate>
            </ListView>
        </StackLayout>
    </ContentPage>

What is wrong in this syntax?

Is there a specific documentation for MAUI binding?

Upvotes: 5

Views: 5965

Answers (2)

JSlice
JSlice

Reputation: 51

Some more helpful hints if you separated your views into their own namespace:

<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="AppName.Views.UsersPage"
             x:Name="Parent"
             xmlns:local="clr-namespace:AppName.ViewModels"
             xmlns:views="clr-namespace:AppName.Views"             
             Title="Users Page">

Note the xml namespace for "views"

Then the full Command binding with all the above becomes:

Command="{Binding Path=AcceptCommand, Source={RelativeSource AncestorType={x:Type views:UsersPage}}}"

The you'll need the following Command in the ViewModel class:

public class UsersViewModel
{
 ...
   public Command AcceptCommand;
 ...
}

Upvotes: 1

Mario Vernari
Mario Vernari

Reputation: 7304

In the first snippet, you have a comma missing and a closing brace more than needed:

<Button Text="Do it"
    Command="{Binding Path=SelectTab, 
                      RelativeSource={RelativeSource AncestorType={x:Type ParentPage}}}"
/>

Upvotes: 6

Related Questions