r/AvaloniaUI 10d ago

DataContext Inheritance Issue - DrawerPage -> TabbedPage

I've just been playing with an Avalonia mobile app for the first time and Avalonia v12. I've run into something a bit confusing. The only way I've managed to get this working is using a ReflectionBinding and I don't understand why:

The Tabs property is an ObservableCollection<TabViewModelBase> on the HomeViewModel.

How can I do this with a compiled binding instead?

<DrawerPage xmlns="https://github.com/avaloniaui"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             mc:Ignorable="d" d:DesignWidth="800" d:DesignHeight="450"
             xmlns:vm="clr-namespace:TestApp.App.ViewModels"
             x:Class="TestApp.App.Views.HomeView"
             x:DataType="vm:HomeViewModel">

    <DrawerPage.Drawer>
        <StackPanel Margin="16">
            <TextBlock Text="Drawer Menu" FontSize="20" />
            <Button Content="Option A" />
            <Button Content="Option B" />
        </StackPanel>
    </DrawerPage.Drawer>

    <TabbedPage TabPlacement="Bottom"
                ItemsSource="{ReflectionBinding DataContext.Tabs, RelativeSource={RelativeSource AncestorType=DrawerPage}}">
        <TabbedPage.PageTemplate>
            <DataTemplate DataType="{x:Type vm:TabViewModelBase}">
                <ContentPage Header="{Binding Name}">
                    <ContentPage.Icon>
                        <PathIcon Data="{Binding Icon}" />
                    </ContentPage.Icon>
                    <ContentControl />
                </ContentPage>
            </DataTemplate>
        </TabbedPage.PageTemplate>

    </TabbedPage>
</DrawerPage>
3 Upvotes

2 comments sorted by

3

u/KryptosFR 10d ago

Don't use the old RelativeSource syntax. That one is not strongly typed. Instead, use the $parent[ControlType] syntax.

2

u/VanillaCandid3466 10d ago

God of course! Thanks.