Reputation: 4775
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
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
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