Best method for overloading a ContentPage to add controls to all pages?

Jesse Knott 686 Reputation points
2021-04-16T18:05:37.41+00:00

Hello,
I'm trying to add Ads to an app which has a lot of pages in it.
Rather than adding the ads code to every page individually, I was thinking it would be easier to create a template that overloads the pages.

How can I create a page, that has controls within it, then embeds the content of the actual page I want in the center of it?

I could then set an internal flag in the BaseViewModel.cs to overload or hide the ads based on a flag for purchased vs free version.

I'm thinking that it is not really possible, or that it would be more cumbersome than just adding conditional code to each page. It's just there are 20+ pages to add it to, and I'd rather not have 20 places that I would have to make single changes to if I update the ads code.

Basically this is what I am thinking about

TemplateContentPage.xaml

<ContentPage
    x:Class="MyApp.Views"
    xmlns="http://xamarin.com/schemas/2014/forms"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
    xmlns:d="http://xamarin.com/schemas/2014/forms/design"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">
    <ContentPage.Content>
        <ScrollView>
            <StackLayout>
                <MyAdViewControl />

                <Original Page content/>

                <MyAdViewControl />
            </StackLayout>
        </ScrollView>
    </ContentPage.Content>
</ContentPage>

Then my regular page

SomePage.xaml

<ContentPage
    x:Class="MyApp.Views"
    xmlns="http://xamarin.com/schemas/2014/forms"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
    xmlns:d="http://xamarin.com/schemas/2014/forms/design"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">
    <ContentPage.Content>
        <ScrollView>
            <StackLayout>
                <MyContent on this page />
            </StackLayout>
        </ScrollView>
    </ContentPage.Content>
</ContentPage>

Any ideas would be much appreciated!

Cheers!

Xamarin
Xamarin
A Microsoft open-source app platform for building Android and iOS apps with .NET and C#.
5,294 questions
{count} votes