How to create a re-useable ContentView as a base view?

Enrico Rossini
206
Reputation points
In my .NET 9 MAUI project, I like to have a base ContentView
to reuse for multiple pages. For that, I created a ContentView
like this:
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage
x:Class="LanguageInUse.Views.BaseAdvView"
xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<ScrollView>
<ContentView x:Name="ContentPlaceholder" />
</ScrollView>
<Label
Grid.Row="1"
Margin="10"
FontSize="Medium"
HorizontalOptions="Center"
Text="Advertisement"
TextColor="Black"
VerticalOptions="Center" />
</Grid>
</ContentPage>
with this code behind:
public partial class BaseAdvView : ContentPage
{
Advertisement? adv;
public BaseAdvView(Advertisement advertisement)
{
InitializeComponent();
adv = advertisement;
}
public void SetContent(View content)
{
ContentPlaceholder.Content = content;
}
}
When I derive a new page from it, I have this XAML:
<?xml version="1.0" encoding="utf-8" ?>
<bav:BaseAdvView
x:Class="LanguageInUse.Views.MainPage"
xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:bav="clr-namespace:LanguageInUse.Views">
<ContentView>
<VerticalStackLayout Padding="30,0" Spacing="25">
<Image
Aspect="AspectFit"
HeightRequest="185"
Source="dotnet_bot.png" />
</VerticalStackLayout>
</ContentView>
</bav:BaseAdvView>
and the code behind is:
public partial class MainPage : BaseAdvView
{
private readonly MainPageViewModel? vm;
private readonly Advertisement adv;
private readonly UserSettings settings;
int count = 0;
public MainPage(MainPageViewModel model, Advertisement advertisement)
: base(advertisement)
{
InitializeComponent();
SetContent(Content);
}
}
The result is that the content from the derive page is shown but the Label
in the base page doesn't.
What is the correct way to create a base page?
Developer technologies | XAML
Sign in to answer