Maui - hover button I see hand like in css

Dani_S 2,866 Reputation points
2023-04-03T02:30:01.46+00:00

Hi,

How I add this funcuality to my button I'm using

.NET 6.

Thanks,

.NET MAUI
.NET MAUI
A Microsoft open-source framework for building native device applications spanning mobile, tablet, and desktop.
2,966 questions
{count} votes

Accepted answer
  1. Wenyan Zhang (Shanghai Wicresoft Co,.Ltd.) 26,946 Reputation points Microsoft Vendor
    2023-04-03T09:29:23.8466667+00:00

    Hello,

    From other thread you post, you are mainly testing on Windows platform. In WinUI, the mouse cursor can be customized and show the hand like CSS, you can refer to the following code:

    (There is a known issue reported at GitHub- Custom Cursor when hovering over View on Desktop #4552, please follow the progress)

    Creating a new class named ElementExtension in your MAUI project.

    
    #if WINDOWS
    
    using Microsoft.UI.Input;
    using Microsoft.UI.Xaml;
    #endif
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Reflection;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace XXXX//your project's namespace
    {
    #if WINDOWS
    public static class ElementExtension
    {
        public static void ChangeCursor(this UIElement uiElement, InputCursor cursor)
        {
            Type type = typeof(UIElement);
            type.InvokeMember("ProtectedCursor", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.SetProperty | BindingFlags.Instance, null, uiElement, new object[] { cursor });
        }
    }
    #endif
    }
    

    If you have a button in the MainPage like this

    
    <ContentPage ......
                 x:Class="XXXX.MainPage">
    ......
               <Button  x:Name="MyBtn"  .....></Button>
    
    </ContentPage>
    
    

    Please invoke the WinUI feature in MainPage code behind

      public MainPage()
          {
                InitializeComponent();
            this.Loaded += MainPage_Loaded;
          }
    
    
    private void MainPage_Loaded(object sender, EventArgs e)
    {
    #if WINDOWS
            Microsoft.UI.Xaml.Controls.Button btn = (Microsoft.UI.Xaml.Controls.Button)MyBtn.Handler.PlatformView;
    //MyBtn is x:Name for a button in XAML, find the native Windows control by handler
            ElementExtension.ChangeCursor(btn, InputSystemCursor.Create(InputSystemCursorShape.Hand));
    #endif
        }
    

    Best Regards,

    Wenyan Zhang


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful