- Hands-On Mobile Development with .NET Core
- Can Bilgin
- 311字
- 2021-06-24 13:55:37
Simple navigation
Within the Xamarin ecosystem, each platform has its own intrinsic navigation stack and applications are built around those stacks. Developers are responsible for maintaining these stacks in order to create the desired UX flow for users.
In order to navigate between pages, Xamarin.Forms exposes a Navigation service, which can be used together with the NavigationPage abstract page implementation. In other words, NavigationPage cannot be categorized as a page type to provide content for users, however, it is a crucial component to maintain the navigation stack, as well as the navigation bar, within Xamarin.Forms applications.
In our sample, we are navigating from ListItemView to ItemView. After this navigation, on iOS, you will notice that the title of the first page is inserted as back-button text in the navigation bar. Additionally, since the Title property is used for the ListItemView (that is, List), the text is additionally displayed in the navigation bar.
The creation of this navigation infrastructure is achieved by creating a NavigationPage and passing the desired page as the root of the navigation stack (looking at App.xaml.cs):
public App ()
{
InitializeComponent();
MainPage = new NavigationPage(new ListItemView());
}
The navigation from one page to the next is handled within the ItemTapped event handler for ListView:
private void Handle_ItemTapped(object sender, Xamarin.Forms.ItemTappedEventArgs e)
{
var itemView = new ItemView();
itemView.BindingContext = e.Item;
Navigation.PushAsync(itemView);
}
Prior to Xamarin.Forms 3.2, the only way to customize what and how the navigation bar was displayed was using some form of native customization (for example, a custom renderer for NavigationPage). Nevertheless, you can now add custom elements to the navigation bar using the TitleView dependency property of a navigation page.
Using the ListItemView page for this illustration, we can add the following XAML section to our ContentPage:
<NavigationPage.TitleView>
<StackLayout Orientation="Horizontal" VerticalOptions="Center" Spacing="10">
<Image Source="Xamarin.png"/>
<Label
Text="Custom Title View"
FontSize="16"
TextColor="Black"
VerticalTextAlignment="Center" />
</StackLayout>
</NavigationPage.TitleView>
The resulting view will have the defined StackLayout instead of the List title that was previously displayed: