Hand cursor for buttons in UWP

16 March 2016

Pointer Button UWP



The hand (or pointer) cursor is used wildly on websites today. The W3C recommends to use it for links and so all browsers include this behaviour in their default stylesheet. This is also true for Hyperlinks in a RichTextBlock in Windows apps.

But what if you have buttons or other elements that link to pages in your app which do not include this behaviour by default? Another use-case are buttons which trigger actions but need a good visual indicator that they are clickable (besides a PointerOver visual state).

To transform your cursor into a hand when hovering a certain element (in our case a button) you have subscribe to the PointerEntered and PointerExited events of the UI element and change the cursor accordingly in the handler.

You can do this by either using behaviours, attach a property to an element or by extending the UI element. In the following example we create a PointerButton by extending the Button:

public class PointerButton : Button
{
  private static readonly CoreCursor handCursor = new CoreCursor(CoreCursorType.Hand, 1);
  private static readonly CoreCursor arrowCursor = new CoreCursor(CoreCursorType.Arrow, 1);

  public PointerButton() : base()
  {
    PointerEntered += (sender, e) =>
    {
      Window.Current.CoreWindow.PointerCursor = handCursor;
    };
    PointerExited += (sender, e) =>
    {
      Window.Current.CoreWindow.PointerCursor = arrowCursor;
    };
  }
}

The CoreCursor is part of the Windows.UI.Core namespace.

First we set static properties for both cursors we need.
In the constructor we tell the button to change the cursor to a hand when the pointer enters the control and back to the arrow when it leaves.

You can use this for all UI elements as UIElement implements both events.

I haved published a demo on github: PointerButton. For a more sophisticated implementation (as an attached property) take a look at the WinRTXAMLToolkit code.

comments powered by Disqus