Creating Cross-Platform Apps with Xamarin: A Complete Guide for Modern Mobile Development

2.78K 0 0 0 0

📘 Chapter 3: Building Shared UI with Xamarin.Forms

🧭 What You’ll Learn

In this chapter, you’ll explore:

  • The structure of Xamarin.Forms UI
  • How to build interfaces using XAML and C#
  • Layout options like StackLayout, Grid, and FlexLayout
  • Controls and inputs (Button, Entry, ListView, etc.)
  • Navigation techniques (NavigationPage, TabbedPage, Shell)
  • Styling and theming UI components
  • Creating reusable components
  • Handling platform-specific design needs in shared UI

Let’s build beautiful, cross-platform UIs with Xamarin.Forms.


🌐 What is Xamarin.Forms?

Xamarin.Forms is a cross-platform UI toolkit that allows you to build a shared user interface in XAML (Extensible Application Markup Language) and/or C#, which renders natively on Android, iOS, and UWP (Windows).

With Xamarin.Forms, you write your UI once and have it render using native controls under the hood.


️ Project Structure

When you create a Xamarin.Forms project, you’ll typically see:

css

 

MyApp/

── MyApp/            ← Shared project (XAML + logic)

── MyApp.Android/    ← Android-specific code

── MyApp.iOS/        ← iOS-specific code

All the UI lives in the shared project, inside .xaml and .xaml.cs files.


️ Defining UI in XAML

Sample: Basic XAML Page

xml

 

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"

             x:Class="MyApp.MainPage">

  <StackLayout Padding="30">

    <Label Text="Welcome to Xamarin.Forms" FontSize="24" />

    <Entry Placeholder="Enter name" />

    <Button Text="Say Hello" Clicked="OnHelloClicked" />

  </StackLayout>

</ContentPage>

Corresponding C# Code (MainPage.xaml.cs)

csharp

 

public partial class MainPage : ContentPage

{

    public MainPage()

    {

        InitializeComponent();

    }

 

    private void OnHelloClicked(object sender, EventArgs e)

    {

        DisplayAlert("Hello", "Welcome to Xamarin!", "OK");

    }

}


📐 Layout Containers in Xamarin.Forms

Layout

Description

Best Use Case

StackLayout

Stacks children vertically or horizontally

Simple column or row of items

Grid

Defines rows and columns like a table

Complex layouts, form grids

FlexLayout

Wraps and aligns elements flexibly

Responsive layouts with variable sizing

AbsoluteLayout

Places items at fixed coordinates

Overlapping elements

RelativeLayout

Places items relative to each other

Conditional alignment or constraints


StackLayout Example

xml

 

<StackLayout Orientation="Vertical">

  <Label Text="Username" />

  <Entry Placeholder="Type here" />

  <Button Text="Login" />

</StackLayout>


Grid Example

xml

 

<Grid Padding="10">

  <Grid.RowDefinitions>

    <RowDefinition Height="Auto"/>

    <RowDefinition Height="*"/>

  </Grid.RowDefinitions>

  <Grid.ColumnDefinitions>

    <ColumnDefinition Width="Auto"/>

    <ColumnDefinition Width="*"/>

  </Grid.ColumnDefinitions>

 

  <Label Grid.Row="0" Grid.Column="0" Text="Username" />

  <Entry Grid.Row="0" Grid.Column="1" />

  <Label Grid.Row="1" Grid.Column="0" Text="Password" />

  <Entry Grid.Row="1" Grid.Column="1" IsPassword="True" />

</Grid>


🧱 UI Controls in Xamarin.Forms

Control

Purpose

Example Property

Label

Display text

FontSize, TextColor

Entry

Text input field

Placeholder, Text

Button

Tap/clickable button

Clicked, Text

Image

Displays an image

Source, Aspect

Switch

Toggle between true/false

IsToggled

ListView

List of data with templates

ItemsSource, ItemTemplate

CollectionView

New, more flexible list UI

Better performance vs ListView


Sample: ListView with Custom Template

xml

 

<ListView x:Name="PeopleList">

  <ListView.ItemTemplate>

    <DataTemplate>

      <TextCell Text="{Binding Name}" Detail="{Binding Email}" />

    </DataTemplate>

  </ListView.ItemTemplate>

</ListView>

csharp

 

PeopleList.ItemsSource = new List<Person> {

  new Person { Name = "Jane Doe", Email = "jane@example.com" },

  new Person { Name = "John Smith", Email = "john@example.com" }

};


🔁 Navigation in Xamarin.Forms

NavigationPage (Stack-based)

csharp

 

await Navigation.PushAsync(new DetailsPage());

TabbedPage

xml

 

<TabbedPage>

  <ContentPage Title="Home" />

  <ContentPage Title="Profile" />

</TabbedPage>

Shell (Modern app structure)

xml

 

<Shell>

  <TabBar>

    <ShellContent Title="Home" ContentTemplate="{DataTemplate local:HomePage}" />

    <ShellContent Title="Settings" ContentTemplate="{DataTemplate local:SettingsPage}" />

  </TabBar>

</Shell>


🎨 Styling and Theming

Inline Styling

xml

 

<Label Text="Welcome" FontSize="24" TextColor="Blue" />

Global Resource Dictionary (App.xaml)

xml

 

<Application.Resources>

  <Color x:Key="PrimaryColor">#3498db</Color>

  <Style TargetType="Label">

    <Setter Property="TextColor" Value="{StaticResource PrimaryColor}" />

  </Style>

</Application.Resources>


️ Creating Reusable Components

Custom UserControl

MyCardView.xaml:

xml

 

<Frame Padding="10" CornerRadius="8">

  <Label Text="{Binding Title}" FontSize="20" />

</Frame>

Use in a page:

xml

 

<local:MyCardView Title="Hello Xamarin!" />


💻 Handling Platform-Specific UI in Shared Code

Use Device.RuntimePlatform or OnPlatform:

xml

 

<Label Text="Hello!" FontSize="{OnPlatform Android=20, iOS=18}" />

Or in C#:

csharp

 

if (Device.RuntimePlatform == Device.Android)

{

    Padding = new Thickness(10, 20, 10, 10);

}


📋 UI Development Best Practices

  • Use XAML for layout, C# for logic
  • Keep UI components modular and reusable
  • Avoid putting heavy logic in code-behind
  • Use MVVM pattern for larger apps
  • Use Shell for scalable navigation
  • Test UI across both Android and iOS

🧠 When to Use Xamarin.Forms vs Xamarin.Native

Use Case

Xamarin.Forms

Xamarin.Native

Shared UI for both platforms

Highly customized UI per platform

Quick MVP or prototype

Complex animations, graphics

Enterprise dashboards, CRUD apps


Summary

In this chapter, you’ve learned:

  • How to build shared UI with Xamarin.Forms
  • Use of XAML and code-behind logic
  • Common layouts and controls
  • Styling and reusable components
  • Cross-platform navigation and best practices


This makes Xamarin.Forms a powerful and productive choice for building mobile apps across platforms using a single UI codebase.

Back

FAQs


❓1. What is Xamarin and how does it work?

Answer:
Xamarin is a Microsoft-backed open-source framework for building cross-platform mobile applications using C# and .NET. It allows developers to write shared business logic and optionally shared UI using Xamarin.Forms, while still accessing native APIs for iOS, Android, and Windows.

❓2. What is the difference between Xamarin.Forms and Xamarin.Native?

Answer:

  • Xamarin.Forms lets you write a single shared UI in XAML that runs on both Android and iOS.
  • Xamarin.Native (Xamarin.iOS and Xamarin.Android) provides full access to native UI APIs, meaning you must create platform-specific UIs but share backend code.

❓3. Can I build apps for iOS using Xamarin on Windows?

Answer:
Yes, but iOS apps must still be compiled on a Mac build host due to Apple’s restrictions. Visual Studio on Windows can remotely connect to a Mac to build and deploy iOS apps.

❓4. How much code can be shared between platforms in Xamarin?

Answer:
With Xamarin.Forms, you can share 90–95% of your code, including business logic and UI. With Xamarin.Native, you typically share 70–80%, with UI coded separately per platform.

❓5. Is Xamarin still relevant with .NET MAUI coming?

Answer:
Yes. Xamarin remains stable and supported, especially for existing projects. However, new projects are encouraged to use .NET MAUI, the evolution of Xamarin, offering broader platform support and modernized architecture.

❓6. Does Xamarin deliver native performance?

Answer:
Yes. Xamarin apps are compiled into native code (AOT on iOS, JIT on Android) and use native controls, which means the performance is on par with apps built using Swift, Kotlin, or Objective-C.

❓7. What programming language does Xamarin use?

Answer:
Xamarin uses C# as the primary programming language, supported by the .NET platform. You can also use XAML for defining UIs in Xamarin.Forms.

❓8. What tools are required to develop with Xamarin?

  • Visual Studio 2022 or later (with Mobile Development workload)
  • .NET SDK
  • Xamarin SDKs (included with Visual Studio)
  • Mac build machine (for iOS development)

❓9. Can I access device-specific features like camera or GPS?

Answer:
Yes. Xamarin provides bindings to native APIs, and Xamarin.Essentials offers cross-platform access to common features like camera, sensors, geolocation, battery, and connectivity with a unified API.

❓10. What are the alternatives to Xamarin for cross-platform development?

Answer:
Some popular alternatives include:

  • Flutter (Dart-based, Google)
  • React Native (JavaScript-based, Meta)
  • .NET MAUI (Xamarin’s successor, Microsoft)
  • Cordova/Capacitor (Web-based hybrid apps)

Each has its own pros and cons depending on the use case, team skills, and performance requirements.