Search code examples
componentsdrymaui

How to create reusable Components in .NET MAUI?


I have just recently started using .Net MAUI. But now I'm wondering how to use a piece of code, e.g. a self-made navigation bar on all my pages, because it doesn't make sense to write the same code on all 10 pages. I like to know if there is a way to create a component that can be reused like in React or Angular?

PS: This question is not specific to a navigation bar but to the general reuse of code in .NET MAUI.

I have so far watched various videos & articles on this topic, however, it is more about custom controls and did not help me. Most articles corresponded to what was conveyed in this video. I also came across this article, but it didn't help me either.

Thanks for your help :)


Solution

  • First, you can create a new .xaml file named Name.xaml. You can write some codes in it.

    <?xml version="1.0" encoding="utf-8" ?>
    <ContentView xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
                 xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
                 x:Class="CusComponents.Name">
        <ContentView.Content>
    
            <StackLayout Padding="10">
    
    
                <Label Text="Name" FontAttributes="Bold" />
    
    
                <Label Text="First name" />
    
                <Entry x:Name="FirstName" Placeholder="First name" />
    
    
                <Label Text="Last name" />
    
                <Entry x:Name="LastName" Placeholder="Last name" />
    
    
            </StackLayout>
    
        </ContentView.Content>
    </ContentView>
    

    Second, you can use it in the page you want like this. You need to add an xmlns reference to the top of the XML file– this is like a using statement in a C# file. Using the namespace structure for the sample project, this will be xmlns:custom_components="clr-namespace:CusComponents".

      <?xml version="1.0" encoding="utf-8" ?>
        <ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
                     xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
                     xmlns:custom_components="clr-namespace:CusComponents"
                     x:Class="CusComponents.MainPage">
        
            <custom_components:Name />
        
        </ContentPage>
    

    Here is the view of the code:

    enter image description here