Introduction .NET MAUI, a cross-platform framework, empowers developers to build native mobile and desktop applications using C#...

.NET MAUI - Swipe View .NET MAUI - Swipe View

A blog about android developement

Introduction

.NET MAUI, a cross-platform framework, empowers developers to build native mobile and desktop applications using C# and XAML. It enables the creation of apps that seamlessly operate on Android, iOS, macOS, and Windows, all from a unified codebase. This open-source platform is an advancement of Xamarin Forms, expanding its reach to desktop scenarios while enhancing UI controls for improved performance and extensibility.


In this article, we will see how to use SwipeView in .NET MAUI project. SwipeView is a container control that wraps around an item of content, and provides context menu items that are revealed by a swipe gesture.


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

SwipeView defines the following attributes:

  • LeftItems: This property, of type SwipeItems, represents the swipe items accessible when swiping the control from the left side.
  • RightItems: This property, of type SwipeItems, represents the swipe items accessible when swiping the control from the right side.
  • TopItems: This property, of type SwipeItems, represents the swipe items accessible when swiping the control from top to bottom.
  • BottomItems: This property, of type SwipeItems, represents the swipe items accessible when swiping the control from bottom to top.
  • Threshold: This property, of type double, determines the number of device-independent units required to trigger a swipe gesture and fully reveal swipe items.

The SwipeView class additionally introduces three events:

  • SwipeStarted: This event is triggered when a swipe commences. It is accompanied by a SwipeStartedEventArgs object that includes a property named SwipeDirection of type SwipeDirection.
  • SwipeChanging: Raised during the progression of a swipe, the SwipeChanging event provides a SwipeChangingEventArgs object. This object encompasses a SwipeDirection property of type SwipeDirection and an Offset property of type double.
  • SwipeEnded: When a swipe concludes, the SwipeEnded event is raised. Its accompanying SwipeEndedEventArgs object contains a SwipeDirection property of type SwipeDirection and an IsOpen property of type bool.

Here's an example demonstrating how to create a SwipeView in XAML.

<SwipeView>
	<SwipeView.LeftItems>
		<SwipeItems>
			<SwipeItem Text="Favorite"
					   IconImageSource="heart.png"
					   BackgroundColor="LightGreen"
					   Invoked="OnFavoriteSwipeItemInvoked" />
		</SwipeItems>
	</SwipeView.LeftItems>
	<SwipeView.RightItems>
		<SwipeItems>
			<SwipeItem Text="Delete"
					   IconImageSource="delete.png"
					   BackgroundColor="LightPink"
					   Invoked="OnDeleteSwipeItemInvoked" />
		</SwipeItems>
	</SwipeView.RightItems>
	<!-- Content -->
	<Grid BackgroundColor="LightGray">
		<Label Text="Swipe Right or Left"
			   HorizontalOptions="Center"
			   VerticalOptions="Center" />
	</Grid>
</SwipeView>

In this example, we will use the listview to display the swipe view and the full example below

<?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="MauiSwipeView.MainPage">

    <ListView x:Name="list">
        <ListView.ItemTemplate>
            <DataTemplate>
                <ViewCell>
                    <SwipeView>
                        <SwipeView.LeftItems>
                            <SwipeItems>
                                <SwipeItem Text="Favorite"
										   IconImageSource="heart.png"
										   BackgroundColor="LightGreen"
										   Invoked="OnFavoriteSwipeItemInvoked" />
                            </SwipeItems>
                        </SwipeView.LeftItems>
                        <SwipeView.RightItems>
                            <SwipeItems>
                                <SwipeItem Text="Delete"
										   IconImageSource="delete.png"
										   BackgroundColor="LightPink"
										   Invoked="OnDeleteSwipeItemInvoked" />
                            </SwipeItems>
                        </SwipeView.RightItems>
                        <!-- Content -->
                        <Grid BackgroundColor="LightGray">
                            <Label Text="Swipe Right or Left"
								   HorizontalOptions="Center"
								   VerticalOptions="Center" />
                        </Grid>
                    </SwipeView>
                </ViewCell>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>

</ContentPage>

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

Introduction .NET MAUI, a cross-platform framework, empowers developers to build native mobile and desktop applications using C# and...

MOPUP (Alternative of Rg.Plugin.Popup) in .NET MAUI MOPUP (Alternative of Rg.Plugin.Popup) in .NET MAUI

A blog about android developement

Introduction

.NET MAUI, a cross-platform framework, empowers developers to build native mobile and desktop applications using C# and XAML. It enables the creation of apps that seamlessly operate on Android, iOS, macOS, and Windows, all from a unified codebase. This open-source platform is an advancement of Xamarin Forms, expanding its reach to desktop scenarios while enhancing UI controls for improved performance and extensibility.

Mopups is a replacement for the "Rg.Plugins.Popups" plugin for Xamarin. Mopups intends to provide a similar experience to this plugin, however also clean up the code base and provide forward looking enhancements.


In this article, we will see how we can see the alternative to Rg.Plugin.Popup - MOPUP Page in .NET MAUI project.

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

  • Open Nuget Package Manager. Search MOPUPS and click install to the install the plugins in the projects.

Implementation

Initialize Mopups

In your MauiProgram.cs file, inside the CreateMauiAppBuilder method, include a call to .ConfigureMopups() on the host builder to set up the Mopups library:

using Mopups;
// ... 
public static MauiApp CreateMauiAppBuilder()
{
    var builder = MauiApp.CreateBuilder();
    // Other configurations
    builder.ConfigureMopups();
    builder.Services.AddSingleton<IPopupNavigation>(MopupService.Instance);
    builder.Services.AddTransient<MainPage>();
    return builder.Build();
}

Create a Custom PopupPage

Include a new ContentPage in your project and update the base class of the XAML file to PopupPage. Don't forget to add the required namespace declaration for the Mopups.Pages namespace:
<?xml version="1.0" encoding="utf-8" ?>
<mopup:PopupPage xmlns="http://xamarin.com/schemas/2014/forms"
                 xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
                 xmlns:local="clr-namespace:YourNamespace"
                 xmlns:mopup="clr-namespace:Mopups.Pages;assembly=Mopups"
                 x:Class="YourNamespace.YourPopupPage">

    <!-- Your PopupPage content goes here -->

</mopup:PopupPage>

Create and Display the Popup

Open MainPage.xaml.cs add the event to open the popup like below.

public partial class MainPage : ContentPage
{
	IPopupNavigation popupNavigation;

	public MainPage(IPopupNavigation popupNavigation)
	{
		InitializeComponent();

		this.popupNavigation = popupNavigation;
	}

	private void OnCounterClicked(object sender, EventArgs e)
	{
		popupNavigation.PushAsync(new MyPopupPage());
	}
}

Add the following code to close the popup screen

MopupService.Instance.PopAsync();

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

https://github.com/LuckyDucko/Mopups

Introduction You might have noticed that in many Android apps, you need to tap the back button twice to exit. When you tap it once, a ...

Transitioning from Deprecated OnBackPressed in .NET MAUI Transitioning from Deprecated OnBackPressed in .NET MAUI

A blog about android developement

Introduction

You might have noticed that in many Android apps, you need to tap the back button twice to exit. When you tap it once, a message pops up. But if you tap it twice at the same time, you can close the app.


Before Android 13 (which is like the newest version), we used to make this work by changing how the back button behaves in the main part of the app (we call it "MainActivity"). But now, with Android 13, the way we used to do this is not recommended anymore. They have a new method that's better.


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

  • This new method lets you see what will happen if you press the back button before you actually do it. This helps you decide if you want to go back or not. For example, you might choose to stay in the app, go back to the Home screen, or return to a previous page in a web browser.
  • To use this new method, Android 13 has added something called the "OnBackInvokedCallback". This is like a tool that helps you do this new back button behavior. It takes the place of the old way we used to change the back button behavior.
  • Now, instead of using the old way, we have the "OnBackPressedDispatcher" which takes care of handling when you press the back button. It works with the new method we just talked about.
  • class BackPress : OnBackPressedCallback
    {
    	private readonly Activity activity;
    	private long backPressed;
    
    	public BackPress(Activity activity) : base(true)
    	{
    		this.activity = activity;
    	}
    
    	public override void HandleOnBackPressed()
    	{
    		var navigation = Microsoft.Maui.Controls.Application.Current?.MainPage?.Navigation;
    		if (navigation is not null && navigation.NavigationStack.Count <= 1 && navigation.ModalStack.Count <= 0)
    		{
    			const int delay = 2000;
    			if (backPressed + delay > DateTimeOffset.UtcNow.ToUnixTimeMilliseconds())
    			{
    				activity.FinishAndRemoveTask();
    				Process.KillProcess(Process.MyPid());
    			}
    			else
    			{
    				Toast.MakeText(activity, "Close", ToastLength.Long)?.Show();
    				backPressed = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
    			}
    		}
    	}
    }
    
  • You'll want to take charge by overriding the HandleOnBackPressed method. The code inside this method closely resembles what you previously had in OnBackPressed.
  • In the last lap of this process, we're going to slot in this callback. You can achieve this by extending the OnCreate method of your MainActivity:
protected override void OnCreate(Bundle? savedInstanceState)
{
	base.OnCreate(savedInstanceState);
    OnBackPressedDispatcher.AddCallback(this, new BackPress(this));
}

Full Code:

using Android.App;
using Android.Content.PM;
using Android.OS;
using Android.Widget;
using AndroidX.Activity;

namespace MauiOnBackPressed;

[Activity(Theme = "@style/Maui.SplashTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation | ConfigChanges.UiMode | ConfigChanges.ScreenLayout | ConfigChanges.SmallestScreenSize | ConfigChanges.Density)]
public class MainActivity : MauiAppCompatActivity
{
    protected override void OnCreate(Bundle? savedInstanceState)
    {
        base.OnCreate(savedInstanceState);
        OnBackPressedDispatcher.AddCallback(this, new BackPress(this));
    }
}
class BackPress : OnBackPressedCallback
{
    private readonly Activity activity;
    private long backPressed;

    public BackPress(Activity activity) : base(true)
    {
        this.activity = activity;
    }

    public override void HandleOnBackPressed()
    {
        var navigation = Microsoft.Maui.Controls.Application.Current?.MainPage?.Navigation;
        if (navigation is not null && navigation.NavigationStack.Count <= 1 && navigation.ModalStack.Count <= 0)
        {
            const int delay = 2000;
            if (backPressed + delay > DateTimeOffset.UtcNow.ToUnixTimeMilliseconds())
            {
                activity.FinishAndRemoveTask();
                Process.KillProcess(Process.MyPid());
            }
            else
            {
                Toast.MakeText(activity, "Close", ToastLength.Long)?.Show();
                backPressed = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
            }
        }
    }
}

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

https://developer.android.com/reference/androidx/activity/OnBackPressedDispatcher

Introduction .NET MAUI, a cross-platform framework, empowers developers to build native mobile and desktop applications using C# and...

Flyout Page in .NET MAUI Flyout Page in .NET MAUI

A blog about android developement

Introduction

.NET MAUI, a cross-platform framework, empowers developers to build native mobile and desktop applications using C# and XAML. It enables the creation of apps that seamlessly operate on Android, iOS, macOS, and Windows, all from a unified codebase. This open-source platform is an advancement of Xamarin Forms, expanding its reach to desktop scenarios while enhancing UI controls for improved performance and extensibility.


In this article, we will see how we can implement Flyout Page in .NET MAUI project.

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

To create a flyout page in a Xamarin.Forms application, you can follow these steps:

  • Add a new page as AppFlyoutPage (XAML Flyout Page) and add the following code.
    <FlyoutPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
                xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
                xmlns:local="clr-namespace:MauiFlyoutPage"
                x:Class="MauiFlyoutPage.AppFlyoutPage">
        <FlyoutPage.Flyout>
            <local:MenuPage x:Name="flyoutPage" />
        </FlyoutPage.Flyout>
        <FlyoutPage.Detail>
            <NavigationPage>
                <x:Arguments>
                    <local:FirstPage />
                </x:Arguments>
            </NavigationPage>
        </FlyoutPage.Detail>
    </FlyoutPage>
  • Then create a content page "MenuPage" which will be used as master page and add the following code.
    <?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="MauiFlyoutPage.MenuPage"
                 Title="MenuPage">
        <VerticalStackLayout VerticalOptions="Center"
                             HorizontalOptions="Center">
            <Button 
                x:Name="btn"
                x:FieldModifier="public"
                Text="Open Second Page"
                VerticalOptions="Center" 
                HorizontalOptions="Center"/>
        </VerticalStackLayout>
    </ContentPage>
  • Open code behind and add the following code.
    namespace MauiFlyoutPage;
    
    public partial class AppFlyoutPage : FlyoutPage
    {
    	public AppFlyoutPage()
    	{
    		InitializeComponent();
            flyoutPage.btn.Clicked += OpenSecondPageClicked;
        }
    
        private void OpenSecondPageClicked(object sender, EventArgs e)
        {
            if (!((IFlyoutPageController)this).ShouldShowSplitMode)
                IsPresented = false;
            Detail = new NavigationPage(new SecondPage());
        }
    }
  • Here, "flyoutPage.btn" present in the master screen and accessed from the flyout screen using XAML field modifier."
  • In the same way, created two pages as "FirstPage" and "SecondPage" to navigate between the screens in the flyout menu.
  • Now, when we running the application, can able see a flyout menu on the left side and the detail content on the right side. Tapping on the button in the flyout master will update the detail content accordingly.

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

https://learn.microsoft.com/en-us/dotnet/maui/user-interface/pages/flyoutpage

Introduction .NET MAUI .NET MAUI, a cross-platform framework, empowers developers to build native mobile and desktop applicatio...

.NET MAUI Barcode Scanner using IRONBARCODE .NET MAUI Barcode Scanner using IRONBARCODE

A blog about android developement

Introduction

.NET MAUI

.NET MAUI, a cross-platform framework, empowers developers to build native mobile and desktop applications using C# and XAML. It enables the creation of apps that seamlessly operate on Android, iOS, macOS, and Windows, all from a unified codebase. This open-source platform is an advancement of Xamarin Forms, expanding its reach to desktop scenarios while enhancing UI controls for improved performance and extensibility.


Using .NET MAUI, you have the capability to develop applications that can run on multiple platforms such as Android, iOS, MacOS, and Windows, all from a single codebase.


.NET MAUI allows for efficient cross-platform development, reducing the need for separate codebases for each platform and simplifying the maintenance and updates of your application.


.NET MAUI saves time and effort and makes it easier to maintain your apps. Visual Studio 2022 is avail with dotnet 7 with .Net Maui app development


In this article, we will see how we can implement a QR code or barcode scanner in the .NET MAUI project using IronBarcode Library.


IronBarcode: C# Barcode Library

The IronBarcode library simplifies barcode detection in .NET applications with its intuitive APIs and eliminates the need for intricate barcode object creation. It offers a wide range of QR code and barcode formats such as Code 39, Code 128, and PDF417.


As a versatile .NET library, it can also function as a QR code reader, decoding input data into readable text from various sources like images and streams. This article explores how to leverage the IronBarcode library for QR code scanning in .NET MAUI applications, providing a comprehensive guide.


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 IronBarcode Library

To install the IronBarcode library via the NuGet Packages Console, simply execute the following command or visit the Nuget package website or search in the Nuget package Manager to download the latest version of the library.

Install-Package BarCode

Implementation of File Picker functionality

Ironbarcode library will read the barcode from the selected image and provide the result. For File Picker functionality, visit the official .NET MAUI essentials link and set up all the mentioned steps in the link.

Designing the screen

In this tutorial, we are using Image, Button, and Editor controls. You can change the design as per your preferences.

<?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="MAUI_Barcode.MainPage">

    <ScrollView>
        <VerticalStackLayout
            Spacing="25"
            Padding="30,0"
            VerticalOptions="Center">

            <Button
                x:Name="ImageSelect"
                Text="Select Barcode"
                SemanticProperties.Hint="Select Image"
                Clicked="SelectBarcode"
                HorizontalOptions="Center" />
            <Image
                x:Name="barcodeImage"
                SemanticProperties.Description="Selected Barcode"
                HeightRequest="200"
                HorizontalOptions="Center" />
            <Editor x:Name="outputText"
                Placeholder="Output text"
                HeightRequest="100"
                WidthRequest="500"
                    />
        </VerticalStackLayout>
    </ScrollView>

</ContentPage>

Here,

  • Button - used to select barcode images that need to be read.
  • Image - used to display the selected barcode image.
  • Editor - used to display the scanned result from Iron Barcode Library.

Functionality of the screen

  • Add a click event for the button to select the image like below. This event will allow the app to select the barcode image.
    private async void SelectBarcode(object sender, EventArgs e)
    {
    	var images = await FilePicker.Default.PickAsync(new PickOptions
    	{
    		PickerTitle = "Pick Barcode/QR Code Image",
    		FileTypes = FilePickerFileType.Images
    	});
    	var imageSource = images.FullPath.ToString();
    	barcodeImage.Source = imageSource;
    	var result = BarcodeReader.Read(imageSource).First().Text;
    	outputText.Text = result;	
    }
  • Once the barcode image is selected, the File Picker will return the full path of the file.
  • We will assign the file path to the image control to preview the selected image.
  • As well as the selected image's file path will be sent as input to the barcode read library.
  • Once the input is processed, the library will return the scanned output as a result of the barcode read function. This output will be assigned to the editor control for displaying the result in human-readable text.

Full Code

using IronBarCode;

namespace MAUI_Barcode;

public partial class MainPage : ContentPage
{

	public MainPage()
	{
		InitializeComponent();
	}

	private async void SelectBarcode(object sender, EventArgs e)
	{
		var images = await FilePicker.Default.PickAsync(new PickOptions
		{
            PickerTitle = "Pick Barcode/QR Code Image",
            FileTypes = FilePickerFileType.Images
		});
		var imageSource = images.FullPath.ToString();
		barcodeImage.Source = imageSource;
		var result = BarcodeReader.Read(imageSource).First().Text;
		outputText.Text = result;
		
    }
}

Output

Upon selecting the barcode, the editor will display a screenshot similar to the one below, with the output text of the QR Code visible.

Before selecting the barcode, similar to other platforms as well:

After selecting the barcode:

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

This article detailed the process of barcode reading in a .NET MAUI application using IronBarcode. IronBarcode proves to be a comprehensive solution equipped with essential tools for barcode operations. Functioning as a QR code reader, IronBarcode delivers accurate and expected output, even when dealing with intricate barcodes. Furthermore, it offers the flexibility to create and customize barcodes using a variety of fonts.


IronBarcode is available for free for development purposes, but a license must be purchased for commercial use. To obtain information about the licensing options, please refer to the following link: https://ironsoftware.com/csharp/barcode/licensing

Introduction .NET MAUI, a cross-platform framework, empowers developers to build native mobile and desktop applications using C# and...

Dynamic Status Bar in .NET MAUI Dynamic Status Bar in .NET MAUI

A blog about android developement

Introduction

.NET MAUI, a cross-platform framework, empowers developers to build native mobile and desktop applications using C# and XAML. It enables the creation of apps that seamlessly operate on Android, iOS, macOS, and Windows, all from a unified codebase. This open-source platform is an advancement of Xamarin Forms, expanding its reach to desktop scenarios while enhancing UI controls for improved performance and extensibility.


In this article, we will see how we can implement Dynamic Status Bar in .NET MAUI project.

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

Screen Design:

As a first point, we need to implement the screen design as per our requirement. In this tutorial, we will use 3 buttons like in the following code block.

<?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="MauiStatusBarBehaviour.MainPage">

    <ScrollView>
        <VerticalStackLayout
            Spacing="25"
            Padding="30,0"
            VerticalOptions="Center">

            <Button
                Text="Blue"
                SemanticProperties.Hint="Counts the number of times you click"
                Clicked="OnBlueClicked"
                HorizontalOptions="Center" />

            <Button
                Text="Green"
                SemanticProperties.Hint="Counts the number of times you click"
                Clicked="OnGreenClicked"
                HorizontalOptions="Center" />

            <Button
                Text="Default"
                SemanticProperties.Hint="Counts the number of times you click"
                Clicked="OnDefaultClicked"
                HorizontalOptions="Center" />

        </VerticalStackLayout>
    </ScrollView>

</ContentPage>

Methods:

To implement this, we can implement in the following methodlogies.

  • Applying Behaviour in XAML.
  • Applying Behaviour in Code behind.
  • Applying without behaviour in Code behind.

In this article, we are going to see "Applying without behaviour in Code behind.".

  • Just install the .NET MAUI community toolkit to your project.
    Install-Package CommunityToolkit.Maui -Version 3.1.0
  • Add it to the MauiProgram.cs
    var builder = MauiApp.CreateBuilder();
    builder
    .UseMauiApp<App>()
    .UseMauiCommunityToolkit()
    .ConfigureFonts(fonts => {
        fonts.AddFont("OpenSans-Regular.ttf", "OpenSansRegular");
        fonts.AddFont("OpenSans-Semibold.ttf", "OpenSansSemibold");
    });
  • Add event in code behind for each button click and apply the below code.
    CommunityToolkit.Maui.Core.Platform.StatusBar.SetColor(statusBarColor);
    CommunityToolkit.Maui.Core.Platform.StatusBar.SetStyle(StatusBarStyle.LightContent);

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

https://learn.microsoft.com/en-us/dotnet/communitytoolkit/maui/behaviors/statusbar-behavior

Introduction .NET MAUI, a cross-platform framework, empowers developers to build native mobile and desktop applications using C# and ...

Localisation in .NET MAUI Localisation in .NET MAUI

A blog about android developement

Introduction

.NET MAUI, a cross-platform framework, empowers developers to build native mobile and desktop applications using C# and XAML. It enables the creation of apps that seamlessly operate on Android, iOS, macOS, and Windows, all from a unified codebase. This open-source platform is an advancement of Xamarin Forms, expanding its reach to desktop scenarios while enhancing UI controls for improved performance and extensibility.


In this article, we will see how we can implement Localisation in .NET MAUI project.


Advantages of Localisation

  • Localisation improves user experience by providing content and language that is culturally relevant and easily understandable to users in different regions, increasing engagement and satisfaction.
  • It expands market reach by making products or services accessible to a global audience, tapping into new markets and driving business growth.
  • Localisation helps build trust and credibility with international customers by demonstrating a commitment to their specific needs and preferences, fostering stronger relationships and customer loyalty.

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

Screen Design:

As a first point, we need to implement the screen design as per our requirement. In this tutorial, we will use 3 controls - 2 labels, and button like in the following code block.

<?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"
             xmlns:resource="clr-namespace:MauiLocalization"
             x:Class="MauiLocalization.MainPage">

    <ScrollView>
        <VerticalStackLayout
            Spacing="25"
            Padding="30,0"
            VerticalOptions="Center">

            <Image
                Source="dotnet_bot.png"
                SemanticProperties.Description="Cute dot net bot waving hi to you!"
                HeightRequest="200"
                HorizontalOptions="Center" />

            <Label
                Text="{x:Static resource:LangResources.Helloworld}"
                SemanticProperties.HeadingLevel="Level1"
                FontSize="32"
                HorizontalOptions="Center" />

            <Label
                Text="{x:Static resource:LangResources.WelcomeNote}"
                SemanticProperties.HeadingLevel="Level2"
                SemanticProperties.Description="Welcome to dot net Multi platform App U I"
                FontSize="18"
                HorizontalOptions="Center" />

            <Button
                x:Name="CounterBtn"
                Text="Change to Tamil"
                SemanticProperties.Hint="Counts the number of times you click"
                Clicked="OnCounterClicked"
                HorizontalOptions="Center" />

        </VerticalStackLayout>
    </ScrollView>

</ContentPage>

Create RESX file

In this step, we will see the steps to create RESX file.

  • In the Solution Explorer, right-click on the project or folder where you want to add the RESX file.
  • Select "Add" from the context menu and then choose "New Item" or "New Folder" if you want to organize your resources in a separate folder.
  • In the "Add New Item" dialog box, search for "Resource File" or navigate to "General" -> "Text File" and name the file with the .resx extension.
  • Click the "Add" button to create the resource file.
  • We created two resources file. One is default and another one prefixed with the language code.
    1. LangResources.resx
    2. LangResources.ta.resx (Contains the resource equivalent in tamil)

RESX Files in XAML

  • To utilize your resources, you first need to import the XML namespace associated with them.
  • xmlns:resource="clr-namespace:MauiLocalization"
  • Then, you can access your strings by using the [x:Static](https://learn.microsoft.com/en-us/xamarin/xamarin-forms/xaml/xaml-basics/xaml-markup-extensions#the-xstatic-markup-extension) markup extension, treating them as properties.
    Text="{x:Static resource:LangResources.Helloworld}"

Language Update

  • Add click event to the button to change language based on the language code of the resource file.
    private void OnCounterClicked(object sender, EventArgs e)
    {
    	if (CounterBtn.Text.Contains("Tamil"))
    	{
    		LangResources.Culture = new CultureInfo("ta");
    		CounterBtn.Text = "Change to English";
    	}
    	else
    	{
    		LangResources.Culture = CultureInfo.InvariantCulture;
    		CounterBtn.Text = "Change to Tamil";
    	}
    	App.Current.MainPage = new MainPage();
    }
  • Here, "App.Current.MainPage = new MainPage();" is used to refresh page once the language changed
  • Then, we will add the below block in the page constructor to retain the language change once the button clicked and page refreshed.
    if (LangResources.Culture != null && LangResources.Culture.TwoLetterISOLanguageName.Contains("ta"))
    {
    	CounterBtn.Text = "Change to English";
    }
    else
    {
    	CounterBtn.Text = "Change to Tamil";
    }

Full Code:

Demo

Android:

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

https://learn.microsoft.com/en-us/dotnet/core/extensions/resources

Introduction .NET MAUI, a cross-platform framework, empowers developers to build native mobile and desktop applications using C#...

File Picker in .NET MAUI File Picker in .NET MAUI

A blog about android developement

Introduction

.NET MAUI, a cross-platform framework, empowers developers to build native mobile and desktop applications using C# and XAML. It enables the creation of apps that seamlessly operate on Android, iOS, macOS, and Windows, all from a unified codebase. This open-source platform is an advancement of Xamarin Forms, expanding its reach to desktop scenarios while enhancing UI controls for improved performance and extensibility.


In this article, we will see how we can implement a File Picker in the .NET MAUI project.


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:

As a first point, we need to implement the screen design as per our requirement. In this tutorial, we will use 3 controls - button, image, and label like in the following code block.


<?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="MauiFilePicker.MainPage">

    <ScrollView>
        <VerticalStackLayout
            Spacing="25"
            Padding="30"
            VerticalOptions="Start">

            <Button
                x:Name="ImageSelect"
                Text="Select Barcode"
                SemanticProperties.Hint="Select Image"
                Clicked="SelectBarcode"
                HorizontalOptions="Center" />
            <Label x:Name="outputText"
                   Padding="10"/>
            <Image
                x:Name="barcodeImage"
                SemanticProperties.Description="Selected Barcode"
                HeightRequest="200"
                HorizontalOptions="Center" />
        </VerticalStackLayout>
    </ScrollView>

</ContentPage>

Here,

  • Button - used to select images from device.
  • Image - used to display the selected image.
  • Label - used to display the file path once the image selected through file picker.

Functional part

  • Add a click event for the button to select the image like below.
    private async void SelectBarcode(object sender, EventArgs e)
    {
    	var images = await FilePicker.Default.PickAsync(new PickOptions
    	{
    		PickerTitle = "Pick Barcode/QR Code Image",
    		FileTypes = FilePickerFileType.Images
    	});
    	var imageSource = images.FullPath.ToString();
    	barcodeImage.Source = imageSource;
    	outputText.Text = imageSource;
    }

    Here,

    • FileTypes: The default file types available for selection in the FilePicker are FilePickerFileType.Images, FilePickerFileType.Png, and FilePickerFileType.Videos. However, if you need to specify custom file types for a specific platform, you can create an instance of the FilePickerFileType class. This allows you to define the desired file types according to your requirements.
    • PickerTitle: The PickOptions.PickerTitle is presented to the user and its behavior varies across different platforms.

    Full Code:

    Demo

    Android:
    android
    Windows:
    windows

    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

    https://learn.microsoft.com/en-us/dotnet/maui/platform-integration/storage/file-picker