In this article, you can learn about how to create equal-width tab items and enable horizontal scrolling to access items that exceed the visible area in the .NET MAUI TabView. This can be achieved by customizing the HeaderItemTemplate in the TabView.
To create a TabView with equal width for all tab items and enable horizontal scrolling, follow these steps:
- Define the TabView: Start by defining the
TabView
in your XAML. - Set the HeaderItemTemplate: Use the
HeaderItemTemplate
to specify how each tab item should be displayed. This template will allow you to set a common width for all tab items and enable horizontal scrolling when the number of items exceeds the visible area.
Here is an example of how to implement this:
Model
public class Model
{
public string? Name { get; set; }
}
ViewModel
public class ViewModel : INotifyPropertyChanged
{
private ObservableCollection<Model>? tabHeaderCollection;
public ObservableCollection<Model>? TabHeaderCollection
{
get { return tabHeaderCollection; }
set { tabHeaderCollection = value;
OnPropertyChanged(nameof(TabHeaderCollection)); }
}
...
public ViewModel()
{
TabHeaderCollection = new ObservableCollection<Model>()
{
new Model(){Name = "Call"},
new Model(){Name = "Favourite"},
new Model(){Name = "Contacts"},
new Model(){Name = "More"},
new Model(){Name = "Help"},
new Model(){Name = "Info" },
new Model(){Name = "About"},
new Model(){Name = "Settings"},
};
}
}
XAML
<tabView:SfTabView x:Name="tabView"
ItemsSource="{Binding TabHeaderCollection}">
<tabView:SfTabView.HeaderItemTemplate>
<DataTemplate>
<HorizontalStackLayout Spacing="2">
<Label FontAttributes="Bold"
WidthRequest="70"
HorizontalTextAlignment="Center"
VerticalTextAlignment="Center"
Text="{Binding Name}"/>
</HorizontalStackLayout>
</DataTemplate>
</tabView:SfTabView.HeaderItemTemplate>
<tabView:SfTabView.Items>
<tabView:SfTabItem>
<tabView:SfTabItem.Content>
<!-- Content for the first tab -->
</tabView:SfTabItem.Content>
</tabView:SfTabItem>
<!-- Additional tab items can be added here -->
</tabView:SfTabView.Items>
</tabView:SfTabView>
By following the above steps, you can create a Syncfusion TabView with equal-width tab items and horizontal scrolling functionality. This enhances the user experience by allowing easy navigation through multiple tabs.
Output