Showing posts with label .NET MAUI Development. Show all posts

Adding custom fonts in .NET MAUI (Multi-platform App UI) is a powerful way to improve your app’s design and branding, making it stand ...

How to Apply Custom Fonts in .NET MAUI How to Apply Custom Fonts in .NET MAUI

A blog about android developement

.NET MAUI Development

Adding custom fonts in .NET MAUI (Multi-platform App UI) is a powerful way to improve your app’s design and branding, making it stand out to users across all platforms, including Android, iOS, Windows, and macOS. In this guide, we’ll go through each step required to integrate custom fonts into your .NET MAUI app effectively, helping you achieve a polished, professional look.


Why Use Custom Fonts in .NET MAUI?

Custom fonts provide numerous benefits:

  • Brand Consistency: Reinforce your brand identity by using fonts that align with your style.
  • Improved Readability: Choose fonts that enhance the readability and aesthetics of your app, improving the user experience.
  • Unique Design: Differentiate your app from others by using custom fonts that reflect the purpose and personality of your app.

Adding custom fonts in .NET MAUI is simple and can significantly impact your app's overall design.


Steps to Add Custom Fonts in .NET MAUI

This tutorial breaks down the process into three essential steps:

  1. 1. Add the Font File to Your .NET MAUI Project
  2. 2. Register the Font in MauiProgram.cs
  3. 3. Use the Custom Font in Your XAML or C# Code

Let’s go through each step in detail.


Step 1: Add the Font File to Your .NET MAUI Project

  • Download the Font: Find a .ttf (TrueType Font) or .otf (OpenType Font) file of your desired font.
  • Place the Font in the Correct Folder: Drag and drop the font file into the Resources/Fonts folder in your .NET MAUI project. This step is crucial because .NET MAUI loads custom fonts directly from this folder.
  • Example: If your font file is named MyCustomFont.ttf, place it in Resources/Fonts.

Step 2: Register the Font in MauiProgram.cs

After adding the font file to your project, the next step is to register it in MauiProgram.cs to ensure .NET MAUI recognizes it.

  • Open MauiProgram.cs in your project.
  • Locate the ConfigureFonts Method: Inside the CreateMauiApp method, find ConfigureFonts and add a new line to register your font file. Here’s how it should look:
    builder.ConfigureFonts(fonts =>
    {
        fonts.AddFont("MyCustomFont.ttf", "MyCustomFontAlias");
    });
    
    • "MyCustomFont.ttf" is the font file name located in Resources/Fonts.
    • "MyCustomFontAlias" is the alias name for the font, which you will use to apply the font in XAML or C#.

Step 3: Use the Custom Font in XAML or C#

With the font registered, it’s now ready to use in your UI.


Using the Font in XAML

To apply the custom font to a control in XAML, use the FontFamily property with the alias you created.

<Label Text="Hello, .NET MAUI!"
       FontFamily="MyCustomFontAlias"
       FontSize="24"
       TextColor="Black"/>

Using the Font in C#

If you prefer to set the font programmatically in C#, you can apply it like this:

Label label = new Label
{
    Text = "Hello, .NET MAUI!",
    FontFamily = "MyCustomFontAlias",
    FontSize = 24,
    TextColor = Colors.Black
};

Tips for Successful Font Integration

  • Check File Names: Ensure that the font file name in MauiProgram.cs matches the actual file name, including case sensitivity.
  • Confirm Licensing: Verify the font’s licensing if you’re using it commercially to avoid copyright issues.
  • Compatibility: Test the font across all supported platforms to make sure it appears correctly on Android, iOS, Windows, and macOS.

Benefits of Using Custom Fonts in .NET MAUI

Custom fonts bring a range of benefits:

  • Consistent Appearance: Once set up, the font will appear consistently across all platforms.
  • Enhanced User Experience: A well-chosen font can make your app more user-friendly and visually appealing.
  • Cross-Platform Design: MAUI makes it easy to use custom fonts without additional platform-specific coding, simplifying cross-platform development.

Wrapping Up

Custom fonts can transform the look and feel of your .NET MAUI app, making it more engaging and unique. By following these steps, you’ll be able to easily add and apply custom fonts across all pages in your app. This customization not only enhances user experience but also boosts your app's professionalism and appeal. With .NET MAUI, you can bring your app's design to life with fonts that make an impression! Start experimenting with different fonts and see how they can elevate your app's style.

Introduction In this tutorial, we will show you how to implement a long press gesture in .NET MAUI using TouchBehavior from the MAUI C...

Detect Long Press in .NET MAUI App using TouchBehavior Detect Long Press in .NET MAUI App using TouchBehavior

A blog about android developement

.NET MAUI Development

Introduction

In this tutorial, we will show you how to implement a long press gesture in .NET MAUI using TouchBehavior from the MAUI Community Toolkit. Learn how to trigger long press events or commands with parameters and see a live example of updating a button image on a successful long press.


Quick Links:


Project Setup:

  • Launch Visual Studio 2022, and in the start window click Create a new project to create a new project.
  • In the Create a new project window, select MAUI in the All project types drop-down, select the .NET MAUI App template, and click the Next button:
  • In the configure your new project window, name your project, choose a suitable location for it, and click the Next button:
  • In the Additional information window, click the Create button:
  • Once the project is created, we can able to see the Android, iOS, Windows and other running options in the toolbar. Press the emulator or run button to build and run the app

Install Plugin

We need to install the "CommunityToolkit.MAUI" by searching in nuget manager and click "Install" to install the plugin

Implementation

Here, we will add the long press behaviour to the image control and you can use as per your need:

  • Add the below code in the xaml file to have wire-up the event or command between the designer and view model. Add Namespace
    xmlns:toolkit="http://schemas.microsoft.com/dotnet/2022/maui/toolkit"
  • Add the following code in your element. In this example, I used Image control
    <Image.Behaviors>
          <toolkit:TouchBehavior LongPressCommand="LongPressCommand" LongPressDuration="2000" />
    </Image.Behaviors>
  • The event code will be look like the below
    LongPressCommand = new Command(() =>
    {
    	count++;
    
    	if (count == 1)
    		CounterBtn.Text = $"Long pressed {count} time";
    	else
    		CounterBtn.Text = $"Long pressed {count} times";
    
    	SemanticScreenReader.Announce(CounterBtn.Text);
    });

Download Code:

You can download the code from GitHub. If you have any doubts, feel free to post a comment. If you liked this article, and it is useful to you, do like, share the article & star the repository on GitHub.

Video Tutorial and Demo:

Introduction This article explores the concept of .NET MAUI handlers and how they are used in development. Handlers act as a bridge bet...

.NET MAUI - Handlers .NET MAUI - Handlers

A blog about android developement

.NET MAUI Development

Introduction

This article explores the concept of .NET MAUI handlers and how they are used in development. Handlers act as a bridge between virtual views and native views on each platform. In simpler terms, they are responsible for instantiating the underlying native view and mapping the cross-platform control API to the native view API. This essentially allows developers to use the same code across different platforms without worrying about the underlying implementation details.


Key concepts of handlers include property mappers and command mappers. These mappers define what actions are taken when a property or command changes. Handlers also support lifecycle events that allow developers to perform actions when a handler is created or changed.


Quick Links:


Project Setup:

  • Launch Visual Studio 2022, and in the start window click Create a new project to create a new project.
  • In the Create a new project window, select MAUI in the All project types drop-down, select the .NET MAUI App template, and click the Next button:
  • In the configure your new project window, name your project, choose a suitable location for it, and click the Next button:
  • In the Additional information window, click the Create button:
  • Once the project is created, we can able to see the Android, iOS, Windows and other running options in the toolbar. Press the emulator or run button to build and run the app

Implementation

Here's a simple example for a .NET MAUI Entry handler:

  • Conditional Compilation: #if ANDROID and #endif are conditional compilation directives. They ensure the code within them is only compiled for the Android platform and similar to other platforms as well.
  • Entry Handler Customization:  This code customizes the appearance of Entry controls with the name "BorderlessEntry".
    Microsoft.Maui.Handlers.EntryHandler.Mapper.AppendToMapping("BorderlessEntry", (handler, view) =>
    {
        if (view is Entry)
        {
            #if ANDROID
            handler.PlatformView.SetBackgroundColor(Microsoft.Maui.Graphics.Colors.Beige.ToAndroid());
            #elif IOS
            handler.PlatformView.BorderStyle = UIKit.UITextBorderStyle.None;
            #elif WINDOWS
            handler.PlatformView.BorderThickness = new Microsoft.UI.Xaml.Thickness(10);
            #endif
        }
    });
    
  • It uses the EntryHandler.Mapper.AppendToMapping method to register a custom mapping for this specific named control.
  • The lambda expression defines what happens when an Entry with the name "BorderlessEntry" is encountered.
  • Inside the lambda, it checks if the view is indeed an Entry control.
  • Then, depending on the platform (Android, iOS, or Windows), it applies platform-specific styling:
    • On Android, the background color is set to beige.
    • On iOS, the border style is removed to create a borderless look.
    • On Windows, a border thickness of 10 is applied.

This code demonstrates how to customize the appearance of an Entry control in .NET MAUI using handlers. By registering a custom mapping for "BorderlessEntry", you can achieve a platform-specific, borderless look for entries with that specific name. This allows for targeted styling without affecting all Entry controls in your app.


Download Code:

You can download the code from GitHub. If you have any doubts, feel free to post a comment. If you liked this article, and it is useful to you, do like, share the article & star the repository on GitHub.

Conclusion:

You can customize various other aspects of the Entry control using platform-specific properties and methods within the handler. This approach allows for a more granular control over the appearance of your UI elements on different platforms while maintaining cross-platform compatibility.

Introduction Welcome to our latest blog post, where we delve into the dynamic world of app development using .NET MAUI! In this comp...

Data Grid Control for .NET MAUI (Free plugin to Sort, Filter & Show Data) Data Grid Control for .NET MAUI (Free plugin to Sort, Filter & Show Data)

A blog about android developement

.NET MAUI Development

Introduction

Welcome to our latest blog post, where we delve into the dynamic world of app development using .NET MAUI! In this comprehensive guide, we explore the intricacies of the "DataGrid Control for .NET MAUI," an exceptional free plugin designed to streamline your data management process. Discover how this plugin empowers developers to effortlessly sort, filter, and display data, enhancing user experiences within cross-platform applications.


In our latest article, we unveil the power of the "DataGrid Control for .NET MAUI," an invaluable plugin that simplifies the complexities of data management in cross-platform app development. As the demand for seamless data visualization and interaction grows, this free plugin emerges as a game-changer for .NET MAUI enthusiasts.


Quick Links:


Project Setup:

  • Launch Visual Studio 2022, and in the start window click Create a new project to create a new project.
  • In the Create a new project window, select MAUI in the All project types drop-down, select the .NET MAUI App template, and click the Next button:
  • In the configure your new project window, name your project, choose a suitable location for it, and click the Next button:
  • In the Additional information window, click the Create button:
  • Once the project is created, we can able to see the Android, iOS, Windows and other running options in the toolbar. Press the emulator or run button to build and run the app

Install Plugin:

In this steps, we will see the steps to install "akgul.Maui.DataGrid" in Visual Studio 2022:
  • Access NuGet Package Manager: In Visual Studio, right-click on your .NET MAUI project in the Solution Explorer. From the context menu, select "Manage NuGet Packages."
  • Search for "akgul.Maui.DataGrid": In the NuGet Package Manager, click on the "Browse" tab. In the search bar, type "akgul.Maui.DataGrid" and hit Enter. The package should appear in the search results.
  • Select and Install the Package: Once you find "akgul.Maui.DataGrid" in the search results, click on it to select it. Ensure you choose the appropriate version compatible with your .NET MAUI project. Click on the "Install" button to begin the installation process.
  • Accept License Agreement: During the installation, you may be prompted to accept the license agreement. Review the terms and conditions and click on the "Accept" button to proceed.
  • Wait for Installation to Complete: Visual Studio will download and install the package along with its dependencies. This process may take a few moments, depending on your internet connection speed.
  • Verify Installation: After the installation is complete, verify that there are no error messages in the Output window. This indicates a successful installation of the "akgul.Maui.DataGrid" package.

Implementation

Add Namespace in XAML:

In your .NET MAUI XAML files where you intend to use the DataGrid, make sure to add the appropriate XML namespace. For example:

xmlns:dg="clr-namespace:Maui.DataGrid;assembly=Maui.DataGrid"

Adjust the namespace and assembly name based on the specifics of the DataGrid component you installed.


Implement DataGrid in Your XAML:

You can now implement the DataGrid control in your XAML files using the namespace you added. For example:

<dg:DataGrid RefreshingEnabled="True"
             BackgroundColor="White"
                     IsRefreshing="{Binding Refreshing}"
                     PullToRefreshCommand="{Binding OnDataGridRefreshCommand}"
                     SelectionEnabled="True"
                     SelectedItem="{Binding SelectedItem}"
                     RowHeight="70"
                     HeaderHeight="70"
                     ItemsSource="{Binding Items}"
                     HeaderBackground="Red">

    <dg:DataGrid.NoDataView>
        <Label Text="Nothing to see here" HorizontalOptions="Center" VerticalOptions="Center" />
    </dg:DataGrid.NoDataView>
    <dg:DataGrid.Columns>
        <dg:DataGridColumn Title="Image" PropertyName="Image" Width="150" SortingEnabled="False">
            <dg:DataGridColumn.CellTemplate>
                <DataTemplate>
                    <Image Source="{Binding}" HorizontalOptions="Center" VerticalOptions="Center"
                           Aspect="AspectFit" HeightRequest="60" />
                </DataTemplate>
            </dg:DataGridColumn.CellTemplate>
        </dg:DataGridColumn>
        <dg:DataGridColumn Title="Name" PropertyName="Name" Width="100"/>
        <dg:DataGridColumn Title="Location" PropertyName="Location"  Width="100"/>
        <dg:DataGridColumn Title="Population" PropertyName="Population"  Width="100"/>
        <dg:DataGridColumn Title="Latitude" PropertyName="Latitude"  Width="100"/>
        <dg:DataGridColumn Title="Longitude" PropertyName="Longitude"  Width="100"/>
    </dg:DataGrid.Columns>
    <dg:DataGrid.RowsBackgroundColorPalette>
        <dg:PaletteCollection>
            <Color>#e1e1e1</Color>
            <Color>#ffffff</Color>
        </dg:PaletteCollection>
    </dg:DataGrid.RowsBackgroundColorPalette>
</dg:DataGrid>

The above code snippet represents a DataGrid component in .NET MAUI application. Let's break down the properties and their meanings in the context of this DataGrid:

  • RefreshingEnabled="True": Indicates that the DataGrid supports pull-to-refresh functionality. Users can pull down to refresh the data displayed in the grid.
  • BackgroundColor="White": Sets the background color of the entire DataGrid component to white.
  • IsRefreshing="{Binding Refreshing}": Binds the IsRefreshing property of the DataGrid to a boolean property named "Refreshing" in the underlying ViewModel. This property likely controls the visual indication of whether the DataGrid is currently refreshing data.
  • PullToRefreshCommand="{Binding OnDataGridRefreshCommand}": Binds the pull-to-refresh action to a command named "OnDataGridRefreshCommand" in the ViewModel. This command is executed when the user performs a pull-to-refresh gesture.
  • SelectionEnabled="True": Allows users to select rows in the DataGrid.
  • SelectedItem="{Binding SelectedItem}": Binds the selected item in the DataGrid to a property named "SelectedItem" in the ViewModel. This property holds the currently selected item in the grid.
  • RowHeight="70": Sets the height of each row in the DataGrid to 70 units.
  • HeaderHeight="70": Sets the height of the header row in the DataGrid to 70 units.
  • ItemsSource="{Binding Items}": Binds the DataGrid to a collection of items represented by the "Items" property in the ViewModel. Each item in this collection corresponds to a row in the DataGrid.
  • HeaderBackground="Red": Sets the background color of the header row to red.
  • dg:DataGrid.NoDataView: Defines a custom view to be displayed when there is no data to show in the DataGrid. In this case, a Label with the text "Nothing to see here" is centered both horizontally and vertically.
  • dg:DataGrid.Columns: Specifies the columns to be displayed in the DataGrid.
  • dg:DataGrid.RowsBackgroundColorPalette: Defines a color palette for alternating row colors in the DataGrid.

This code snippet configures a DataGrid component with specific properties and templates, allowing users to view and interact with data in a visually appealing manner.


The Code Behind or MVVM view model properties are similar to listview control and no specific code required


Full Code:

Demo

Download Code:

You can download the code from GitHub. If you have any doubts, feel free to post a comment. If you liked this article, and it is useful to you, do like, share the article & star the repository on GitHub.

References

To learn more about Swipe View