Setting a cursor for .NET MAUI VisualElement

Setting a cursor for .NET MAUI VisualElement

10 May 2023

.NET MAUI/Xamarin

Buy Me A Coffee

Hello!

This blog post is devoted to setting a cursor for .NET MAUI VisualElement.

Let's start with defining a CursorIcon enumeration:

It will be used for mapping platform-specific cursors.

Platform-Specific Implementations

Android

Create a new file named CursorExtensions.cs in the Platforms\Android folder and add the following code:

Please pay attention. The PointerIcon API works on Android 24 and later.

iOS

Create a new file named CursorExtensions.cs in the Platforms\iOS folder and add the following code:

UIPointerStyle.Create can be created from different shapes. However, I haven't found predefined cursors for our CursorIcon. The option, for now, is to create a custom icon from the path.

MacCatalyst

Create a new file named CursorExtensions.cs in Platforms\MacCatalyst folder and add the following code:

Unlike iOS, MacCatalyst has an NSCursor class with predefined cursors. UIHoverGestureRecognizer helps us to set a custom cursor on the Hover event.

Windows

To set the custom cursor on Windows, create a new file named CursorExtensions.cs in the Platforms\Windows folder and add the following code:

UIElement is a base class for all UI elements. It has a protected ProtectedCursor property that we can use to set a custom cursor. It is a very odd decision to make this property protected. We need to use reflection to set its value.

Using the Custom Cursor in Your Application

With this code, we set the cursor to a "Hand" style when the mouse pointer is over the "MyVisualElement" control.

Creating the Attached Property

In order to set a custom cursor from XAML, let's create an attached property.

Create a new file in the root of the project named CursorBehavior.cs and paste the following code:

Now that we have implemented the attached property for setting custom cursors, let's use it in our MainPage.xaml.

Open MainPage.xaml and add the following code inside the ContentPage element:

Windows Cursor

The final code can be found on GitHub.

Happy coding!

Buy Me A Coffee

Related:

Choose the right framework for your next application

A Deep Dive into .NET MAUI, Uno, and Avalonia.

Creating Kanban Board using Xamarin.Forms

This article describes how to create Kanban Board using Xamarin Forms (.NET MAUI) only. Drag & Drop Cards, Set Column WIP, Store data in Local Db.

An unhandled error has occurred. Reload

🗙