For iOS, the title is already displaying in the middle, but for Android, it’s displayed on the left side by default. I want the title to be centered on both platforms. To achieve this, I’m using Shell.TitleView and OnPlatform for Android, but this approach isn’t dynamic—I still have to set the value statically for each page. Since the project has many pages, this isn’t really feasible. Is there any other approach I can use that is more dynamic?
Here is Xaml code
<Shell.TitleView>
<OnPlatform x:TypeArguments="View">
<On Platform="Android">
<Grid VerticalOptions="Center" HorizontalOptions="FillAndExpand"
ColumnDefinitions=".5*, .5*" Padding="0,0,15,0">
<!-- Title Label -->
<Label Grid.Column="0" Text="Sign Up"
TextColor="White"
HorizontalOptions="End"
FontFamily="poppins500"
FontSize="16"
/>
</Grid>
</On>
</OnPlatform>
</Shell.TitleView>
5
This will need updates based on your needs.
Create a BaseContentPage
where you create your TitleView
now if you are using shell you need to keep that and remove the navigation page one and vice versa but I am adding both for someone who comes to this later:
<?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"
x:Name="this"
x:Class="Sample.BaseContentPage">
<Shell.TitleView>
<Grid>
<Label TextColor="Green" Text="{Binding Title,Source={x:Reference this}}" HorizontalTextAlignment="Center" VerticalTextAlignment="Center" />
</Grid>
</Shell.TitleView>
<NavigationPage.TitleView>
<Grid>
<Label TextColor="Green" Text="{Binding Title, Source={x:Reference this}}" HorizontalTextAlignment="Center" VerticalTextAlignment="Center" />
</Grid>
</NavigationPage.TitleView>
</ContentPage>
Any UI changes you need to make to the Title’s label you need to make in the BaseContentPage
.
Once you do this you can use it in any number of pages and all you have to do is set BaseContentPage
as your base class set the Title
of the new page that you need to use it in and voila!
The usage would look something like this:
<?xml version="1.0" encoding="utf-8" ?>
<pages:BaseContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:pages="clr-namespace:Sample"
Title="This is a centered title"
x:Class="Sample.MainPage">
.
.
.
</pages:BaseContentPage>
xaml.cs
public partial class MainPage : BaseContentPage
{
public MainPage()
{
InitializeComponent();
}
}
That’s how it looks on both devices:
iOS | Android |
---|---|