András Tóth‘s professional blog
banditoth.net

Hey there 👋, I’m banditoth a .NET MAUI developer from Hungary.
I write about software development with .NET technologies.

You can find me on:
LinkedIn | Github | StackOverflow | X / Twitter | Threads

Tag: maui

  • Resizing the screen when an Entry gets focused in .NET MAUI

    This content has 7 months. Some of the information in this post may be out of date or no longer work. Please, read this page keeping its age in your mind.

    When an entry field gets focused, the software keyboard appears, potentially covering the entry field. To provide a better user experience, you need to adjust the screen layout so that the entry field remains visible.

    First, create a parent class for your views, deriving from ContentPage, and add a HaveKeyboardOffsetProperty.

    public class ViewBase : ContentPage
    {
        public static readonly BindableProperty HasKeyboardOffsetProperty =
            BindableProperty.Create(nameof(HasKeyboardOffset), typeof(bool), typeof(ViewBase), false);
    
        public bool HasKeyboardOffset
        {
            get => (bool)GetValue(HasKeyboardOffsetProperty);
            set => SetValue(HasKeyboardOffsetProperty, value);
        }
    }
    
    

    iOS Solution:

    Next, create the PageElementMapper class to handle the keyboard appearance and adjust the screen layout.

    public class PageElementMapper
    {
        private static double _contentOriginalHeight;
        private static Thickness _contentOriginalMargin;
    
        public static void Map(IElementHandler handler, IElement view)
        {
            if (view is ViewBase viewData)
            {
                UIKeyboard.Notifications.ObserveWillShow((sender, args) =>
                {
                    if (viewData.HasKeyboardOffset)
                    {
                        _contentOriginalHeight = viewData.Content.Height;
                        _contentOriginalMargin = viewData.Content.Margin;
                        viewData.Content.HeightRequest = _contentOriginalHeight - args.FrameEnd.Height;
                        viewData.Content.Margin = new Thickness(0, args.FrameEnd.Height, 0, 0);
                    }
                });
    
                UIKeyboard.Notifications.ObserveWillHide((sender, args) =>
                {
                    if (viewData.HasKeyboardOffset)
                    {
                        viewData.Content.HeightRequest = _contentOriginalHeight;
                        viewData.Content.Margin = _contentOriginalMargin;
                    }
                });
            }
        }
    }
    
    

    Finally, register the mapper in the MauiProgram.cs file.

    public static class MauiProgram
    {
        public static MauiApp CreateMauiApp()
        {
            var builder = MauiApp.CreateBuilder();
            builder
                .UseMauiApp<App>()
                .ConfigureMauiHandlers(handlers =>
                {
                    Microsoft.Maui.Handlers.PageHandler.ElementMapper.AppendToMapping("KeyboardOffset", (handler, view) =>
                    {
                        if (view is ViewBase)
                        {
    #if IOS
                            PageElementMapper.Map(handler, view);
    #endif
                        }
                    });
                });
    
            return builder.Build();
        }
    }
    
    

    Android solution:

    On Android, you can use a PropertyChanged method of the HasKeyboardOffset:

        private static void OnHasKeyboardOffsetPropertyChanged(BindableObject bindable, object oldValue, object newValue)
        {
    #if ANDROID
            if (bindable is ViewBase view)
            {
                if (newValue is bool hasOffset)
                    if (hasOffset == true)
                        Microsoft.Maui.Controls.Application.Current.Dispatcher.Dispatch(() =>
                        {
                            Platform.CurrentActivity?.Window?.SetSoftInputMode(Android.Views.SoftInput.AdjustResize);
                        });
                    else
                        Microsoft.Maui.Controls.Application.Current.Dispatcher.Dispatch(() =>
                        {
                            Platform.CurrentActivity?.Window?.SetSoftInputMode(Android.Views.SoftInput.StateUnspecified);
                        });
            }
    #endif
        }
    

    Remarks

    The provided solution offers a way to manage this in .NET MAUI on iOS. However, always be open to improvements and share your solutions with the community for better practices. This might not be the best solution to do it.

  • .NET MAUI Hide software keyboard when tapping out of an Entry on iOS

    This content has 7 months. Some of the information in this post may be out of date or no longer work. Please, read this page keeping its age in your mind.

    To hide the software keyboard when the user taps outside the entry field, set the HideSoftInputOnTapped property to True in your ContentPage definition.

    &lt;ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
                 xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
                 x:Class="MyMauiApp.MainPage"
                 HideSoftInputOnTapped="True">
    
        &lt;StackLayout Padding="10">
            &lt;Entry Placeholder="Tap here to enter text" />
        &lt;/StackLayout>
    &lt;/ContentPage>
    
    

    Please note that the HideSoftInputOnTapped property might not work as expected when tapping on certain controls like ScrollView. In such cases, you might need to implement a custom behavior to handle keyboard dismissal.

  • Resolving SQLite issues for .NET MAUI

    This content has 7 months. Some of the information in this post may be out of date or no longer work. Please, read this page keeping its age in your mind.

    Recently, while working on ExampleApp, we faced two significant errors and found effective solutions for both. Here’s a detailed account of the problems and their resolutions.

    System.TypeInitializationException

    System.TypeInitializationException: The type initializer for 'SQLite.SQLiteConnection' threw an exception.
     ---> System.DllNotFoundException: e_sqlite3
    

    To resolve this error, we needed to install the latest NuGet package for SQLitePCLRaw.bundle_green. This package ensures that the necessary SQLite libraries are included in the project.

    Add the following package reference with the latest version to your project:

    &lt;PackageReference Include="SQLitePCLRaw.bundle_green" Version="2.1.10" />
    
    

    In the AppDelegate.cs file, add the following line to the CreateMauiApp method:

    protected override MauiApp CreateMauiApp()
    {
        SQLitePCL.raw.SetProvider(new SQLitePCL.SQLite3Provider_sqlite3());
        return MauiProgram.CreateMauiApp();
    }
    

    System.ExecutionEngineException in iOS Release Mode

    System.ExecutionEngineException: Attempting to JIT compile method '(wrapper delegate-invoke) void System.Action`2&lt;ExampleApp.Entites.LocalDatabase.VoucherLite, double>:invoke_callvirt_void_T1_T2 (ExampleApp.Entites.LocalDatabase.VoucherLite,double)' while running in aot-only mode. See https://docs.microsoft.com/xamarin/ios/internals/limitations for more information.
    

    This error occurs due to the JIT compilation attempt in AOT-only mode on iOS. The solution is to install this specific version of the sqlite-net-pcl.
    It will ONLY work with 1.7.355 or below.

    &lt;PackageReference Include="sqlite-net-pcl" Version="1.7.335" />
    

     This solution is also applicable to Xamarin projects.

  • .NET MAUI Android: OverrideBackButtonPress not being hit.

    This content has 7 months. Some of the information in this post may be out of date or no longer work. Please, read this page keeping its age in your mind.

    You might encounter a scenario where the OverrideBackButtonPress method in your Page is not being triggered on Android devices. This can be a frustrating issue, but there’s a straightforward solution that involves modifying your AndroidManifest.xml file.

    The predictive back gesture feature in Android can indeed affect how back button presses are handled in your application. Learn more at: https://developer.android.com/guide/navigation/custom-back/predictive-back-gesture

    Predictive Back Gesture

    Android’s predictive back gesture allows users to preview the destination or action that will occur when they complete a back gesture. In .NET MAUI, the OverrideBackButtonPress method allows you to handle the back button press event in your application. However, if this method is not being called, it could be due to a specific setting in your AndroidManifest.xml file.

    Disabling Predictive Back Gesture

    To ensure your custom back button handling works as expected, you need to disable the predictive back gesture by setting the android:enableOnBackInvokedCallback attribute to false in your AndroidManifest.xml file. This prevents the system from intercepting the back button press and allows your application to handle it.

    <application
        android:label="YourAppName"
        android:icon="@mipmap/ic_launcher"
        android:enableOnBackInvokedCallback="false">
        <!-- Other settings -->
    </application>
    
    

  • Visual Studio for Mac: The target platform identifier was not recognized .NET MAUI

    This content has 9 months. Some of the information in this post may be out of date or no longer work. Please, read this page keeping its age in your mind.

    If you are facing issues on macOS, with the retiring Visual Studio for Mac launching your .NET MAUI app, or restoring the packages on it:

    error NETSDK1139: The target platform identifier android was not recognized.
    error NETSDK1139: The target platform identifier iOS was not recognized.
    error NETSDK1139: The target platform identifier MacCatalyst was not recognized.

    This error can be also recognized from this toolbar:

    Ensure whether you have the correct .NET Workloads installed with the terminal command:

    sudo dotnet workload install maui

    Check whether you have the latest .NET SDK installed on your machine, from the Microsoft’s official website.

    Ensure you have enabled “Use the .NET 8 SDK if installed” in the Visual Studio for Mac’s preferences.