Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
17 views14 pages

Mobileapp Merged

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views14 pages

Mobileapp Merged

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

ITSH2405

Mobile App Development With .NET MAUI


Fundamentals
The process of software development is called the Software Development Lifecycle (SDLC). The lifecycle of
mobile development is not that different from the SLDC for web or desktop applications. The following are the
five (5) phases of the mobile software development lifecycle:
1. Inception: All apps start with an idea. That idea is usually refined into a solid basis for an application.
2. Design: The design phase consists of defining the app's User Experience (UX), such as what the
general layout is, how it works, etc., as well as turning the UX into a proper User Interface (UI) design.
3. Development: Usually the most resource-intensive phase, this is the actual building of the
application.
4. Stabilization: When development is far enough, Quality Assurance (QA) usually begins testing the
application and bugs are fixed. Often, an application will go into a limited beta phase in which a wider
user audience is given a chance to use it, provide feedback, and inform changes.
5. Deployment: In this phase, applications and updates are delivered from developers to users.

.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.

Figure 1. .NET MAUI Supported platforms.

.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.

Figure 2. The .NET MAUI architecture

01 Handout 1 *Property of STI


[email protected] Page 1 of 3
ITSH2405

• .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 Features


.NET MAUI provides a collection of controls that can be used to display data, initiate actions, indicate activity,
display collections, pick data, and more. In addition to a collection of controls, .NET MAUI also provides:
• An elaborate layout engine for designing pages.
• Multiple page types for creating rich navigation types, like drawers.
• Support for data-binding, for more elegant and maintainable development patterns.
• The ability to customize handlers to enhance how UI elements are presented.
• Cross-platform APIs for accessing native device features. These APIs enable apps to access device
features such as the GPS, the accelerometer, and battery and network states.
• Cross-platform graphics functionality, that provides a drawing canvas that supports drawing and
painting shapes and images, compositing operations, and graphical object transforms.
• A single project system that uses multi-targeting to target Android, iOS, macOS, and Windows.
• .NET hot reload, so that you can modify both your XAML and your managed source code while the
app is running, then observe the result of your modifications without rebuilding the app.

.NET MAUI provides cross-platform APIs for native device features. Examples of functionality provided by
.NET MAUI for accessing device features include:

• Access to sensors, such as the accelerometer, compass, and gyroscope on devices.


• Ability to check the device's network connectivity state and detect changes.
• Provide information about the device the app is running on.
• Copy and paste text to the system clipboard between apps.
• Pick single or multiple files from the device.
• Store data securely as key/value pairs.
• Utilize built-in text-to-speech engines to read text from the device.
• Initiate browser-based authentication flows that listen for a callback to a specific app-registered URL.

.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:

01 Handout 1 *Property of STI


[email protected] Page 2 of 3
ITSH2405

• 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/

01 Handout 1 *Property of STI


[email protected] Page 3 of 3
ITSH2405

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.

The Application Class


The App class represents the .NET MAUI application as a whole. It inherits a default set of behaviors from
Microsoft.Maui.Controls.Application. The App class is instantiated and loaded by the bootstrap code for
each platform. The constructor of the App class will, in turn, usually create an instance of the AppShell class
and assign it to the MainPage property. This code controls the first screen the user sees through what is defined
in the AppShell.

The App class also contains:


• Methods for handling life-cycle events, including when the app is sent to the background.
• Methods for creating new Windows for the application. The .NET MAUI application, by default, has a
single window but can create and launch additional windows, which is helpful in desktop and tablet
applications.

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.

This class can consist of three main hierarchical objects:


• FlyoutItem or TabBar: A FlyoutItem represents one or more items in the flyout and should be used
when the navigation pattern for the app requires a flyout. A TabBar represents the bottom tab bar and
should be used when the navigation pattern for the app begins with bottom tabs and doesn't require a
flyout.
• Tab – represents grouped content, navigable by bottom tabs.
• ShellContent – represents the ContentPage objects for each tab.
These objects do not represent any user interface but rather the organization of the app's visual hierarchy. Shell
will take these objects and produce the navigation user interface for the content.

02 Handout 1 *Property of STI


[email protected] Page 1 of 3
ITSH2405

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.

Controls and Layouts


A view can contain a single control, such as a button, label, or text box. Note that a view is also a control so it
can contain another view. However, a user interface restricted to a single control would not be very useful, so
controls are positioned in a layout.

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>

Some of the common controls used to define layouts are:


• VerticalStackLayout and HorizontalStackLayout, optimized stack layouts that lay out controls in
a top-to-bottom or left-to-right stack. A StackLayout is also available, which has a property

02 Handout 1 *Property of STI


[email protected] Page 2 of 3
ITSH2405

named StackOrientation, which can be set to Horizontal or Vertical. On a tablet or phone,


modifying this property in an application code enables the adjustment of the display if the user rotates
the device.
• AbsoluteLayout, which is used to set exact coordinates for controls.
• FlexLayout, is similar to StackLayout, except that it enables wrapping the child controls it contains if
they do not fit in a single row or column. This layout also provides options for alignment and adapting
to different screen sizes. For example, a FlexLayout control can align its child control to the left, right,
or center when arranged vertically. When aligned horizontally, controls can be justified to ensure even
spacing. A horizontal FlexLayout could be used inside a ScrollView to display a horizontally
scrollable series of frames (each frame could be a vertically arranged FlexLayout).
• Grid, which positions its child elements in a grid of rows and columns. Column and row sizes can be
defined, as well as spans, so grid layouts do not necessarily have a "checkerboard look" to them.

Figure 1. Common layout types.

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.

Another useful whitespace setting is the Spacing property of VeticalStackLayout or


HorizontalStackLayout. This is the space between all the children of the layout. This is additive with the
control’s own margin, so the actual whitespace will be margin plus spacing.

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/

02 Handout 1 *Property of STI


[email protected] Page 3 of 3
ITSH2405

User Interface With XAML


Fundamentals
A markup language is a computer language that is used to introduce various elements in a document.
Elements are described using predefined tags. The tags have specific meaning in the context of the domain
where the document is used. For example, you can use Hypertext Markup Language (HTML) to create a
webpage that you can display in a web browser.

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

03 Handout 1 *Property of STI


[email protected] Page 1 of 4
ITSH2405

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.

The MainPage.xaml.cs file looks similar to this:


namespace MyMauiApp;

public partial class MainPage : ContentPage


{
public MainPage()
{
InitializeComponent();
}
}

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.

private void Button_Clicked(object sender, EventArgs e)


{
PhoneDialer.Open(PhoneNumber.Text);
}

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.

03 Handout 1 *Property of STI


[email protected] Page 2 of 4
ITSH2405

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:

private void RadioButton_CheckedChanged(object sender, CheckedChangedEventArgs e)


{
RadioButton button = sender as RadioButton;
levelLabel.Text = $"You have chosen {button.Content}";
}

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.

03 Handout 1 *Property of STI


[email protected] Page 3 of 4
ITSH2405

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/

03 Handout 1 *Property of STI


[email protected] Page 4 of 4
ITSH2405
XAML Pages type double. On iOS, the values are called points. On Android, they're
Layout density-independent pixels.
A layout panel is a .NET MAUI container that holds a collection of child views
and determines their size and position. The layout panels automatically The sample XAML code below shows how to specify a label’s width and height.
recalculate when the size of the app changes. An example is when the user <Label
rotates the device. Text="Hello"
WidthRequest="100"
The typical process for building a .NET MAUI page is to create a layout panel HeightRequest="300"
and then add child views to it. The following are commonly used layout BackgroundColor="Silver" />
panels:
The layout panel reads the values during its sizing calculations and tries to
accommodate the requests if it can. If there is not enough space, the layout
panel is allowed to ignore the values.

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.

04 Handout 1 *Property of STI


[email protected] Page 1 of 4
ITSH2405
• For horizontal alignment, End positions the View on the right-hand var a = new BoxView() { Color = Colors.Silver };
side of the parent layout, and for vertical alignment, it positions the var b = new BoxView() { Color = Colors.Blue };
View at the bottom of the parent layout. var c = new BoxView() { Color = Colors.Gray };
• For horizontal alignment, Fill ensures that the View fills the width of
the parent layout, and for vertical alignment, it ensures that the View stack.Children.Add(a);
fills the height of the parent layout. stack.Children.Add(b);
stack.Children.Add(c);
Sample XAML code:
<StackLayout> Output:
<Label Text="Start" HorizontalOptions="Start" BackgroundColor="Silver" />
<Label Text="Center" HorizontalOptions="Center" BackgroundColor="Silver" />
<Label Text="End" HorizontalOptions="End" BackgroundColor="Silver" />
<Label Text="Fill" HorizontalOptions="Fill" BackgroundColor="Silver" />
</StackLayout>

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>

04 Handout 1 *Property of STI


[email protected] Page 2 of 4
ITSH2405
The following example shows how to set the orientation to Horizontal: The Expands property is designed specifically for StackLayout and allows a
<StackLayout Orientation="Horizontal"> child view to request extra space if there's any available. Here's an example
<BoxView Color="Silver" /> of how the Expands property works:
<BoxView Color="Blue" />
<BoxView Color="Gray" />
</StackLayout>

Output:

Figure 2. Before and after expansion

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.

04 Handout 1 *Property of STI


[email protected] Page 3 of 4
ITSH2405
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/

04 Handout 1 *Property of STI


[email protected] Page 4 of 4

You might also like