Mobileapp Merged
Mobileapp Merged
.NET Multi-platform App UI (.NET MAUI) is a cross-platform framework for creating native mobile and desktop
apps with C# and XAML. .NET MAUI allows you to develop apps that can run on Android, iOS, macOS, and
Windows from a single shared code-base.
.NET MAUI provides a single framework for building the UIs for mobile and desktop apps. The following
diagram shows a high-level view of the architecture of a .NET MAUI app.
• .NET MAUI unifies Android, iOS, macOS, and Windows APIs into a single API that allows a write-once
run-anywhere developer experience while providing deep access to every aspect of each native
platform.
• .NET provides a series of platform-specific frameworks for creating apps: .NET Android, .NET iOS,
.NET macOS, and Windows UI 3 (WinUI 3) library. These frameworks all have access to the same
.NET Base Class Library (BCL).
• BCL abstracts the details of the underlying platform away from your code. The BCL depends on the
.NET runtime to provide the execution environment for your code.
• For Android, iOS, and macOS, the environment is implemented by Mono, an implementation of the
.NET runtime. On Windows, .NET CoreCLR provides the execution environment.
• The various platforms have different ways of defining the user interface for an app, and they provide
varying models for specifying how the elements of a user interface communicate and interoperate. You
can craft the UI for each platform separately using the appropriate platform-specific framework (.NET
Android, .NET iOS, .NET macOS, or WinUI 3), but this approach requires you to maintain a code-base
for each individual family of devices.
In a .NET MAUI app, you write code that primarily interacts with the .NET MAUI API (1). .NET MAUI, then
directly consumes the native platform APIs (3). In addition, app code may directly exercise platform APIs (2), if
required.
.NET MAUI provides cross-platform APIs for native device features. Examples of functionality provided by
.NET MAUI for accessing device features include:
.NET MAUI single project takes the platform-specific development experiences you typically encounter while
developing apps and abstracts them into a single shared project that can target Android, iOS, macOS, and
Windows. .NET MAUI single project provides a simplified and consistent cross-platform development
experience, regardless of the platforms being targeted. .NET MAUI single project provides the following
features:
• A single shared project that can target Android, iOS, macOS, and Windows.
• A simplified debug target selection for running your .NET MAUI apps.
• Shared resource files within the single project.
• A single app manifest that specifies the app title, id, and version.
• Access to platform-specific APIs and tools when required.
• A single cross-platform app entry point.
References:
Bilgin, C. (2021). Mobile development with .NET (2nd ed.). Packt Publishing.
Microsoft. (n.d.). .NET MAUI documentation. Retrieved on August 16, 2023 from https://learn.microsoft.com/en-
us/dotnet/maui/
Visual Controls
Building Blocks
A .NET MAUI project initially contains:
• MauiProgram.cs file – contains the code for creating and configuring the Application object.
• App.xaml and App.xaml.cs files – provide UI resources and create the initial window for the
application.
• AppShell.xaml and AppShell.xaml.cs files – specify the initial page for the application and handle the
registration of pages for navigation routing.
• MainPage.xaml and MainPage.xaml.cs files – define the layout and UI logic for the page displayed by
default in the initial window.
A .NET MAUI project also contains a default set of application resources such as images, icons, fonts, and
default bootstrap code for each platform.
Navigation Structures
Shell
.NET MAUI Shell reduces the complexity of app development by providing the fundamental features that most
apps require, including:
• A single place to describe the visual hierarchy of an app.
• A common navigation user experience.
• A URI-based navigation scheme that permits navigation to any page in the app.
• An integrated search handler.
In a .NET MAUI Shell app, the visual hierarchy of the app is described in a class that subclasses the Shell class.
Pages
Pages are the root of the UI hierarchy in .NET MAUI inside of a Shell. A solution includes a class
called MainPage, which derives from ContentPage, the simplest and most common page type. A content page
displays a single view.
.NET MAUI has several other built-in page types, too, including the following:
• TabbedPage: This is the root page used for tab navigation. A tabbed page contains child page objects,
one for each tab.
• FlyoutPage: This page enables the implementation of a master/detail style presentation. A flyout page
contains a list of items. When selecting an item, a view displaying the details for that item appears.
• NavigationPage: This page provides a hierarchical navigation experience where you can navigate
through pages, forwards and backwards, as desired.
Other page types are available and are mostly used for enabling different navigation patterns in multi-screen
apps.
Views
A content page typically displays a view. A view enables users to retrieve and present data in a specific manner.
• The default view for a content page is a ContentView, which displays items as-is. If the view is shrunk,
items may disappear from the display until the view is resized.
• A ScrollView enables the display of items in a scrolling window; if the window is shrunk, items will be
displayed by scrolling up and down.
• A CarouselView is a scrollable view that lets the user swipe through a collection of items.
• A CollectionView can retrieve data from a named data source and present each item using a template
as a format. There are many other types of views available as well.
A layout defines the rules by which the controls are displayed relative to each other. It is also a control so it can
be added to a view. Looking at the default MainPage.xaml file, a page/view/layout/control hierarchy can be seen
in action. In this XAML code, the VerticalStackLayout element is just another control that enables fine-tuning
the layout of other controls.
<ContentPage ...>
<ScrollView ...>
<VerticalStackLayout>
<Image ... />
<Label ... />
<Label ... />
<Button ... />
</VerticalStackLayout>
</ScrollView>
</ContentPage>
Tuning a Layout
It is useful to add a little breathing space around a control. Each control has a Margin property that is respected
by the layouts. Think of margin as the control pushing others away.
All the layouts also have a Padding property that keeps any of their children from getting close to the border of
the layout. One way to think of this is that all the controls are in a box with padded walls.
References:
Bilgin, C. (2021). Mobile development with .NET (2nd ed.). Packt Publishing.
Microsoft. (n.d.). .NET MAUI documentation. Retrieved on August 16, 2023 from https://learn.microsoft.com/en-
us/dotnet/maui/
Extensible Application Markup Language (XAML) is a declarative language created by Microsoft that is based
on XML. XAML was designed to simplify the process of creating the UI in applications.
UI on XAML will allow the separation of the app’s UI and behavior to make it easier to manage both. Other
benefits include:
• Division of labor: Since XAML is a markup language, it does not require programming knowledge.
Designers can focus on XAML and programmers can focus on writing the code.
• Tooling friendly: It is possible to use a design tool to create the XAML layout for you. You can drag
and drop controls onto a design surface using a graphical experience.
The first step in using XAML to build a UI is instantiating the UI control types. In XAML, the types can be created
using Object Element Syntax, a standard, well-formed XML syntax to declare the element to instantiate. For
example, if you want to declare a label, your XAML element will look like the following: <Label />
The above XAML element will be parsed by the XAML parser to instantiate the object in memory. This is the
same with the following C# code: new Label ();
The next thing to do is instruct the XAML parser to use controls. We add this instruction using a namespace.
An XML namespace is used to specify the location of the information needed to instantiate the XAML elements
that you declare. Namespaces are defined by adding the xmlns attribute to the root element in the XAML
document. Typically, the root element of a XAML document is ContentPage.
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="MyMauiApp.MainPage">
...
</ContentPage>
The two XML namespace (xmlns) declarations refer to URIs on microsoft.com. However, these URIs have no
content, and they function as version identifiers. The first XML namespace declaration means that tags defined
within the XAML file with no prefix refer to classes in .NET MAUI, for example ContentPage. The second
namespace declaration defines a prefix of x. This is used for several elements and attributes that are intrinsic
to XAML itself and supported by other XAML implementations.
At the end of the first tag, the x prefix is used for an attribute named Class. Because the use of this x prefix
is virtually universal for the XAML namespace, XAML attributes such as Class are almost always referred to
as x:Class. The x:Class attribute specifies a fully qualified .NET class name: the MainPage class in the
MyMauiApp namespace. This means that this XAML file defines a new class named MainPage in the
MyMauiApp namespace that derives from ContentPage (the tag in which the x:Class attribute appears).
The x:Class attribute can only appear in the root element of a XAML file to define a derived C# class. This is
the only new class defined in the XAML file. Everything else that appears in a XAML file is instead simply
instantiated from existing classes and initialized.
In XML, attributes are used to describe or provide information about an element. In XAML, attributes are used
to set properties on the underlying type. For example:
<Label Text="Username" TextColor="Black"/>
The above XAML code creates a new Label object and sets the Text and TextColor properties. Since
TextColor uses the Color type and string is the only valid thing that can be used for an XML attribute
value, it is needed to convert the string value to the Color type. A Type Converter is used to convert an
XML attribute value to its correct type.
Event Handling
The Button is the most fundamental interactive control. The Button control defines a Clicked event that is
fired once the Button is tapped. The following code instantiates a Button in XAML.
<Button Text="Dial" Clicked="Button_Clicked"/>
The Clicked event is set to an event handler named Button_Clicked. This handler is located in the xaml.cs
file. Below is a sample method definition:
Upon defining your UI in XAML, you will have to add code to respond to user interaction.
When the Button is tapped, the Button_Clicked method executes. The sender argument is the Button
object responsible for this event. You can use this to access the Button object or to distinguish between
multiple Button objects sharing the same Clicked event.
RadioButton
It is a type of button that allows users to select one option from a set. Each option is represented by one radio
button, and you can only select one radio button in a group. A RadioButton displays text when the Content
property is assigned a string. To group radio buttons, you can set the GroupName property on each radio
button in the group to the same value.
<RadioButton Content="Beginner"
GroupName="levels"
CheckedChanged="RadioButton_CheckedChanged"/>
<RadioButton Content="Intermediate"
GroupName="levels"
CheckedChanged="RadioButton_CheckedChanged"/>
<RadioButton Content="Advanced"
GroupName="levels"
CheckedChanged=”RadioButton_CheckedChanged”/>
<Label x:Name=”levelLabel”/>
The RadioButton control defines a CheckedChanged event that is fired when the IsChecked property
changes. The CheckedChanged event is set to an event handler named RadioButton_CheckedChanged.
This handler is located in the xaml.cs file. Below are sample method definition and output:
SearchBar
It is a user input control used to initiate a search. The SearchBar control supports placeholder text, query
input, search execution, and cancellation. It has a Placeholder property that can be set to define the hint
text in the query input box. The following code instantiates a SearchBar in XAML with the optional
Placeholder property set:
<SearchBar Placeholder="Search items…"/>
A search can be executed using the SearchBar control by attaching an event handler to either the following:
• SearchButtonPressed is called when the user either clicks the search button or presses the
enter key.
• TextChanged is called anytime the text in the query box is changed.
The example below shows an event handler attached to the TextChanged event and uses a ListView to
display search results.
<SearchBar TextChanged="SearchBar_TextChanged"/>
<ListView x:Name="searchResults">
The TextChanged event is set to an event handler named SearchBar_TextChanged. This handler is
located in the xaml.cs file.
References:
Bilgin, C. (2021). Mobile development with .NET (2nd ed.). Packt Publishing.
Microsoft. (n.d.). .NET MAUI documentation. Retrieved on August 28, 2023 from https://learn.microsoft.com/en-
us/dotnet/maui/
Both WidthRequest and HeightRequest cannot be used to tell the actual size
at runtime. To solve this problem, the View base class defines two (2)
additional properties called Width and Height. These properties are of type
double and represent the rendered width and height of a view. You should use
the Width and Height properties in retrieving the size of a view.
There is also a need to set the position of a view. The View base class has
two (2) properties that are used to set the view’s position: VerticalOptions and
HorizontalOptions. These settings influence how the view is positioned within
Figure 1. .NET MAUI common layout panels the rectangle allocated for it by the layout panel. Both properties are of type
LayoutOptions.
• StackLayout – arranges its children in a single row or column.
• Grid – arranges its children in cells that are created by rows and The LayoutOptions structure encapsulates two (2) layout preferences:
columns. • Alignment – the view's preferred alignment, which determines its
• AbsoluteLayout – arranges its children by using x and y coordinates. position and size within its parent layout.
• FlexLayout – arranges its child views like a StackLayout except that • Expansion – used only by a StackLayout, and indicates if the view
you can wrap them if they don't fit into a single row or column. should use extra space if it's available.
If you don't specify the size of a view, it will automatically adjust to be exactly LayoutAlignment is an enumeration that contains four (4) values: Start,
large enough to fit around its content. In building a UI, it is common to control Center, End, and Fill. You can use these values to control how the child view
the view size. is positioned within the rectangle given to it by its layout panel.
• For horizontal alignment, Start positions the View on the left-hand side
The View base class defines two (2) properties that influence the size of a of the parent layout, and for vertical alignment, it positions the View at
view: WidthRequest and HeightRequest. WidthRequest lets you specify the the top of the parent layout.
width, and HeightRequest lets you specify the height. Both properties are of • For horizontal and vertical alignment, Center horizontally or vertically
centers the View.
Output:
StackLayout
Stacking views in a vertical or horizontal list is a common design for user
interfaces. A StackLayout organizes child views in a one-dimensional stack,
either horizontally or vertically. By default, a StackLayout is oriented vertically.
It can also be used as a parent layout that contains other child layouts.
The StackLayout class defines the following properties: StackLayout automatically sizes and positions the views in a vertical list.
• Orientation – represents the direction in which child views are
positioned. The default value of this property is Vertical. The code is simpler in XAML. The XAML parser adds the nested views to
• Spacing – indicates the amount of space between each child view. automatically. See the XAML version below.
The default value of this property is 0. <StackLayout>
<BoxView Color="Silver" />
The following shows how to add three (3) views to a StackLayout using C# <BoxView Color="Blue" />
code. <BoxView Color="Gray" />
</StackLayout>
Output:
Below is an example of setting the Spacing property to 30: The extra space will be divided evenly among all views that request additional
<StackLayout Spacing="30"> space. To request additional space, you replace the LayoutOptions value with
<BoxView Color="Silver" /> one of these values: StartAndExpand, CenterAndExpand, EndAndExpand, or
<BoxView Color="Blue" /> FillAndExpand.
<BoxView Color="Gray" />
</StackLayout>
Output:
The orange box is the view and the gray rectangle represents the extra space
given to it by the Expands property. The view fills the extra space only when
you use the FillAndExpand value. When you use the other values, the extra
space remains empty, but it can't be used by other views in the StackLayout.