Home > Enterprise >  Binding a command to a parent view model in MAUI
Binding a command to a parent view model in MAUI

Time:12-04

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:

  • '}' expected
  • '�' expected

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?

CodePudding user response:

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}}}"
/>
  • Related