xamarin.formsmaui

ContentView as Resource Dictionary


Reusable layout can be have in a ContentView in a seperate file and use like this:

 <StackLayout>
    <local:MyContentView/>
 </StackLayout>

However, is it possible if I want to have the ContentView as a resource dictionary in the same file and use it?. Something like this is what I'm after:

<ContentPage.Resources>
    <ResourceDictionary>
        <ContentView x:Key="MyContentView">
            <!--Some Views-->
        </ContentView>
    </ResourceDictionary>
</ContentPage.Resources>

Then how would I use this key in my StackLayout?


Solution

  • Define the ControlTemplate in the ResourceDictionary and use it in the Xaml:

    <ContentPage.Resources>
        <ResourceDictionary>
    
            <ControlTemplate x:Key="MyContentView">
    
                <Label Text="tttttt" HorizontalOptions="CenterAndExpand" VerticalOptions="CenterAndExpand"/>
                
            </ControlTemplate>
    
    
        </ResourceDictionary>
    </ContentPage.Resources>
    
    <StackLayout>
        <!-- Place new controls here -->
    
        <ContentView ControlTemplate="{StaticResource MyContentView}" HorizontalOptions="CenterAndExpand" VerticalOptions="CenterAndExpand"/>
    
    </StackLayout>