XAML MAUI Basic View Types


These controls(views) are some of the basics in developing interfaces that are to be used in a GUI. You can have these views on the content pages. All of these controls are single-functionality control elements.

Image 

Displays an image.

<Image Source="dotnet_bot.png"
       HeightRequest="200"
       WidthRequest="200"
       HorizontalOptions="Center" />
  • Source="dotnet_bot.png": Path to the image resource.
  • HeightRequest and WidthRequest: Set the image size.
  • HorizontalOptions: Will align the image to the middle of the screen horizontally.

Label

Displays text.

<Label Text="Welcome to .NET MAUI!"
       FontSize="Large"
       TextColor="Blue"
       HorizontalOptions="Center" />
  • Text: Text to display.
  • FontSize="Large": Sets the text size.
  • TextColor="Blue": Sets the color of the text.

Button

Triggers an action when clicked.

<Button Text="Click Me"
        Clicked="OnButtonClicked"
        HorizontalOptions="Center" />
private void OnButtonClicked(object sender, EventArgs e)
{
    DisplayAlert("Alert", "Button clicked!", "OK");
}

Clicked="OnButtonClicked": This is the event handler of the button OnClick event.

ActivityIndicator

Illustrates that an operation is in progress.

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="MauiAppExample.ActivityIndicatorPage">

    <StackLayout Padding="30" VerticalOptions="Center">

        <!-- Header Label -->
        <Label Text="Data Loader Example"
               FontSize="Large"
               HorizontalOptions="Center" />

        <!-- ActivityIndicator -->
        <ActivityIndicator x:Name="LoadingIndicator"
                           IsRunning="{Binding IsLoading}"
                           Color="Blue"
                           HorizontalOptions="Center"
                           VerticalOptions="Center"
                           Margin="0,20,0,20" />

        <!-- Load Data Button -->
        <Button Text="Load Data"
                Clicked="OnLoadDataClicked"
                HorizontalOptions="Center" />

        <!-- Data Loaded Label -->
        <Label x:Name="LoadedDataLabel"
               Text="{Binding LoadedDataText}"
               FontSize="Medium"
               TextColor="Green"
               HorizontalOptions="Center"
               IsVisible="{Binding IsDataLoaded}" />

    </StackLayout>

</ContentPage>
  • x:Name="LoadingIndicator": The name assigned to the indicator.
  • IsRunning="{Binding IsLoading}": Subscribes the IsLoading property. When IsLoading is true the ActivityIndicator executes.
  • Color="Blue":Specifies the color of the indicator.
using System.ComponentModel;
using System.Runtime.CompilerServices;

namespace MauiAppExample
{
    public partial class ActivityIndicatorPage : ContentPage, INotifyPropertyChanged
    {
        // Private fields for property backing
        private bool _isLoading;
        private bool _isDataLoaded;
        private string _loadedDataText;

        public ActivityIndicatorPage()
        {
            InitializeComponent();
            BindingContext = this;
        }

        // Property: Indicates if data is being loaded
        public bool IsLoading
        {
            get => _isLoading;
            set
            {
                _isLoading = value;
                OnPropertyChanged();
            }
        }

        // Property: Indicates if data has been loaded
        public bool IsDataLoaded
        {
            get => _isDataLoaded;
            set
            {
                _isDataLoaded = value;
                OnPropertyChanged();
            }
        }

        // Property: Text for loaded data
        public string LoadedDataText
        {
            get => _loadedDataText;
            set
            {
                _loadedDataText = value;
                OnPropertyChanged();
            }
        }

        // Method: Simulates loading data
        private async void OnLoadDataClicked(object sender, EventArgs e)
        {
            // Start the loading process
            IsLoading = true;
            IsDataLoaded = false;
            LoadedDataText = string.Empty;

            // Simulate a delay (e.g., a network request)
            await Task.Delay(3000);

            // Loading complete
            IsLoading = false;
            IsDataLoaded = true;
            LoadedDataText = "Data Loaded Successfully!";
        }

        // Implement INotifyPropertyChanged to update the UI when properties change
        public event PropertyChangedEventHandler PropertyChanged;

        protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}
  • Implements INotifyPropertyChanged: This interface is used to bind data in to the page and to inform the UI about a property changed event.
  • IsLoading: Determines whether the ActivityIndicator is running or not.
  • IsDataLoaded: Hides or shows the label that displays data when data-loaded property is set to true.
  • LoadedDataText: It comes on after data is loaded; contains the text to be displayed.

CheckBox

Provides the user with an option of a true/fasle checkbox.

<CheckBox IsChecked="True"
          Color="Red" />

DatePicker

Allows users to pick a date.

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="MauiAppExample.DatePickerPage">

    <StackLayout Padding="30" VerticalOptions="Center" HorizontalOptions="Center">

        <!-- Header Label -->
        <Label Text="Select a Date"
               FontSize="Large"
               HorizontalOptions="Center" />

        <!-- DatePicker -->
        <DatePicker x:Name="DateSelector"
                    Date="{Binding SelectedDate}"
                    MinimumDate="2023-01-01"
                    MaximumDate="2025-12-31"
                    DateSelected="OnDateSelected"
                    HorizontalOptions="Center"
                    Margin="0,20,0,20" />

        <!-- Display Selected Date -->
        <Label x:Name="SelectedDateLabel"
               Text="{Binding SelectedDateText}"
               FontSize="Medium"
               TextColor="Green"
               HorizontalOptions="Center" />

        <!-- Reset Button -->
        <Button Text="Reset to Today"
                Clicked="OnResetClicked"
                HorizontalOptions="Center"
                Margin="0,20,0,0" />
    </StackLayout>

</ContentPage>
  • x:Name="DateSelector": Enables users to refer this DatePicker in other code–behind files.
  • Date="{Binding SelectedDate}": Extends itself to the SelectedDate property.
  • MinimumDate / MaximumDate: Sets a valid date range.
  • DateSelected="OnDateSelected": Function that will be called when a date is chosen.
using System.ComponentModel;
using System.Runtime.CompilerServices;

namespace MauiAppExample
{
    public partial class DatePickerPage : ContentPage, INotifyPropertyChanged
    {
        private DateTime _selectedDate;
        private string _selectedDateText;

        public DatePickerPage()
        {
            InitializeComponent();
            BindingContext = this;

            // Initialize default date
            SelectedDate = DateTime.Today;
            SelectedDateText = "Selected Date: " + SelectedDate.ToString("D");
        }

        // Property for the SelectedDate
        public DateTime SelectedDate
        {
            get => _selectedDate;
            set
            {
                _selectedDate = value;
                OnPropertyChanged();
            }
        }

        // Property for displaying the selected date text
        public string SelectedDateText
        {
            get => _selectedDateText;
            set
            {
                _selectedDateText = value;
                OnPropertyChanged();
            }
        }

        // Date Selected Event Handler
        private void OnDateSelected(object sender, DateChangedEventArgs e)
        {
            // Update the SelectedDateText whenever the date changes
            SelectedDateText = "Selected Date: " + e.NewDate.ToString("D");
        }

        // Reset Button Event Handler
        private void OnResetClicked(object sender, EventArgs e)
        {
            // Reset to today's date
            SelectedDate = DateTime.Today;
            SelectedDateText = "Selected Date: " + SelectedDate.ToString("D");
        }

        // INotifyPropertyChanged Implementation
        public event PropertyChangedEventHandler PropertyChanged;

        protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

TimePicker

Allows users to pick a time.

<TimePicker Time="{Binding SelectedTime}"
            Format="t" />
  • Time: Binds to the selected time.
  • Format="t": Sets the display format (e.g., “HH”).

Editor

A multi-line text input field.

<Editor Placeholder="Enter your feedback here..."
        AutoSize="TextChanges" />
  • Placeholder: Body text to be shown when the editor is blank.
  • AutoSize="TextChanges": Child controls Fixed size: No. It can automatically adjust the size according to the size of the content.

Entry

A single-line text input field.

<Entry Placeholder="Enter your name"
       MaxLength="50" />
  • Placeholder: Text displayed when the entry is empty.
  • MaxLength="50": Limits the number of characters.

ImageButton

A button that displays an image.

<ImageButton Source="camera_icon.png"
             Clicked="OnImageButtonClicked"
             HeightRequest="50"
             WidthRequest="50" />
  • Source: The picture which is located on the button.
  • Clicked="OnImageButtonClicked": Event handler corresponds to when the mouse pointer has clicked.

SearchBar

Allows users to enter a search query.

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="MauiAppExample.SearchBarPage">

    <StackLayout Padding="20" VerticalOptions="FillAndExpand">

        <!-- Header Label -->
        <Label Text="Search Fruits"
               FontSize="Large"
               HorizontalOptions="Center" />

        <!-- SearchBar -->
        <SearchBar x:Name="FruitSearchBar"
                   Placeholder="Enter fruit name"
                   TextChanged="OnSearchBarTextChanged"
                   SearchButtonPressed="OnSearchButtonPressed" />

        <!-- ListView to display filtered items -->
        <ListView x:Name="FruitsListView"
                  ItemsSource="{Binding FilteredFruits}"
                  VerticalOptions="FillAndExpand">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <TextCell Text="{Binding}" />
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>

    </StackLayout>

</ContentPage>
  • x:Name="FruitSearchBar": Also, makes you refer to the SearchBar in the code-behind.
  • Placeholder: The text displayed when nothing is typed into the search bar at the top.
  • TextChanged="OnSearchBarTextChanged": Event fired each time the text into the SearchBar is modified.
  • SearchButtonPressed="OnSearchButtonPressed": Event that is executed when the search button has been performed.
  • ItemsSource="{Binding FilteredFruits}": Attached to an array of filtered fruits.
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Runtime.CompilerServices;

namespace MauiAppExample
{
    public partial class SearchBarPage : ContentPage, INotifyPropertyChanged
    {
        private ObservableCollection<string> _allFruits;
        private ObservableCollection<string> _filteredFruits;

        public SearchBarPage()
        {
            InitializeComponent();
            BindingContext = this;

            // Initialize the list of all fruits
            AllFruits = new ObservableCollection<string>
            {
                "Apple", "Banana", "Cherry", "Date", "Elderberry", "Fig", "Grape", "Honeydew",
                "Kiwi", "Lemon", "Mango", "Nectarine", "Orange", "Papaya", "Quince", "Raspberry",
                "Strawberry", "Tangerine", "Ugli Fruit", "Watermelon"
            };

            // Initially, display all fruits
            FilteredFruits = new ObservableCollection<string>(AllFruits);
        }

        // Collection of all fruits
        public ObservableCollection<string> AllFruits
        {
            get => _allFruits;
            set
            {
                _allFruits = value;
                OnPropertyChanged();
            }
        }

        // Collection of filtered fruits to display in the ListView
        public ObservableCollection<string> FilteredFruits
        {
            get => _filteredFruits;
            set
            {
                _filteredFruits = value;
                OnPropertyChanged();
            }
        }

        // TextChanged event handler for SearchBar
        private void OnSearchBarTextChanged(object sender, TextChangedEventArgs e)
        {
            FilterFruits(e.NewTextValue);
        }

        // SearchButtonPressed event handler for SearchBar
        private void OnSearchButtonPressed(object sender, EventArgs e)
        {
            FilterFruits(FruitSearchBar.Text);
        }

        // Method to filter fruits based on search text
        private void FilterFruits(string searchText)
        {
            if (string.IsNullOrWhiteSpace(searchText))
            {
                // If search text is empty, show all fruits
                FilteredFruits = new ObservableCollection<string>(AllFruits);
            }
            else
            {
                // Filter the list based on the search text
                var filtered = AllFruits.Where(fruit => fruit.ToLower().Contains(searchText.ToLower()));
                FilteredFruits = new ObservableCollection<string>(filtered);
            }
        }

        // INotifyPropertyChanged Implementation
        public event PropertyChangedEventHandler PropertyChanged;

        protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}
  • AllFruits: Stores all available fruits.
  • FilteredFruits: Saves the results filtered by the search text. It is linked to this collections to display the results in the ListView.
  • OnSearchBarTextChanged: Activated each time the user enters something in the search line. Contacts FilterFruits to notify him/her of a new list of fruits to be displayed.
  • OnSearchButtonPressed: Activated on the occurrence of the search button in the keyboard. Contacts FilterFruits to get the filtering done.
  • Filtering Method (FilterFruits): The function accepts the search text value – searchText. If searchText is empty: All fruits are shown. Otherwise: Searches AllFruits for specific text by using filters.
  • INotifyPropertyChanged: INotifyPropertyChanged is implemented in order to attain the functionality of the FilteredFruits property in the execution of the view.
  • OnPropertyChanged: Triggers events whenever a property has been changed on an object.

ProgressBar

Shows progress visually.

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="MauiAppExample.ProgressBarPage">

    <StackLayout Padding="30" VerticalOptions="Center">

        <!-- Header Label -->
        <Label Text="Progress Bar Example"
               FontSize="Large"
               HorizontalOptions="Center" />

        <!-- ProgressBar -->
        <ProgressBar x:Name="TaskProgressBar"
                     Progress="0"
                     ProgressColor="Blue"
                     HeightRequest="20"
                     Margin="0,20,0,20" />

        <!-- Start Button -->
        <Button Text="Start Task"
                Clicked="OnStartTaskClicked"
                HorizontalOptions="Center" />

        <!-- Status Label -->
        <Label x:Name="ProgressStatusLabel"
               Text="Press the button to start the task."
               FontSize="Medium"
               HorizontalOptions="Center"
               VerticalOptions="Center" />

    </StackLayout>

</ContentPage>

ProgressBar:

  • x:Name="TaskProgressBar": Name to reference the progress bar in the code-behind.
  • Progress="0": Sets the initial progress to 0%.
  • ProgressColor="Blue": Sets the color of the progress indicator.
using System.ComponentModel;

namespace MauiAppExample
{
    public partial class ProgressBarPage : ContentPage
    {
        public ProgressBarPage()
        {
            InitializeComponent();
        }

        // Event Handler for the Start Button
        private async void OnStartTaskClicked(object sender, EventArgs e)
        {
            // Reset ProgressBar and Status Label
            TaskProgressBar.Progress = 0;
            ProgressStatusLabel.Text = "Task in progress...";

            // Simulate a task with incremental progress
            for (int i = 1; i <= 10; i++)
            {
                // Wait for 500 milliseconds (simulate work)
                await Task.Delay(500);

                // Update the progress (increment by 10% each iteration)
                double progress = (double)i / 10;
                await TaskProgressBar.ProgressTo(progress, 250, Easing.Linear);

                // Update Status Label
                ProgressStatusLabel.Text = $"Progress: {progress * 100}%";
            }

            // Task Completed
            ProgressStatusLabel.Text = "Task Completed!";
        }
    }
}

Slider

Allows users to select a value from a range.

<Slider Minimum="0"
        Maximum="100"
        Value="50" />

Stepper

Allows users to increment or decrement a value.

<Stepper Minimum="0"
         Maximum="10"
         Increment="1"
         ValueChanged="OnStepperValueChanged" />
private void OnStepperValueChanged(object sender, ValueChangedEventArgs e)
{
    DisplayAlert("Value Changed", $"New value: {e.NewValue}", "OK");
}

Switch

A toggle switch.

<Switch IsToggled="True"
        Toggled="OnSwitchToggled" />
private void OnSwitchToggled(object sender, ToggledEventArgs e)
{
    DisplayAlert("Switch Toggled", $"Is now: {e.Value}", "OK");
}

Summary

These basic controls are essential for building rich and interactive user interfaces in .NET MAUI applications:

  • Image: Displays images.
  • Label: Displays text.
  • Button: Responds to user clicks.
  • ActivityIndicator: This option allows the user to make choices from options as true or false.
  • CheckBox: Lets the user select true/false options.
  • DatePicker: Allows date selection.
  • TimePicker: Allows time selection.
  • Editor: Multi-line text input.
  • Entry: Single-line text input.
  • ImageButton: Button with an image.
  • SearchBar: Allows search input.
  • ProgressBar: Displays progress.
  • Slider: Facilitates the possibility of getting one value out of a row of equally spaced numbers.
  • Stepper: Can either increase or decrease the value of a number.
  • Switch: Provides a toggle control.
, ,