Skip to content

Instantly share code, notes, and snippets.

@martinsuchan
Created July 18, 2017 14:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save martinsuchan/7f5511ec6a7fdb213979afe0766bab3f to your computer and use it in GitHub Desktop.
Save martinsuchan/7f5511ec6a7fdb213979afe0766bab3f to your computer and use it in GitHub Desktop.
CoreCursor attached property helper class.
using System.Collections.Generic;
using System.Diagnostics;
using Windows.UI.Core;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Input;
namespace CursorTest
{
public class Cursor : DependencyObject
{
private static readonly CoreCursor DefaultCursor = new CoreCursor(CoreCursorType.Arrow, 1);
private static readonly HashSet<UIElement> AttachedElements = new HashSet<UIElement>();
private static readonly Dictionary<CoreCursorType, CoreCursor> Cursors =
new Dictionary<CoreCursorType, CoreCursor> {{CoreCursorType.Arrow, DefaultCursor}};
public static readonly DependencyProperty UseProperty =
DependencyProperty.RegisterAttached("Use", typeof(CoreCursorType), typeof(Cursor), new PropertyMetadata(CoreCursorType.Arrow));
public static void SetUse(DependencyObject obj, CoreCursorType value)
{
if (!(obj is UIElement element)) return;
lock (AttachedElements)
{
element.SetValue(UseProperty, value);
if (!Cursors.ContainsKey(value))
{
Cursors[value] = new CoreCursor(value, 1);
}
if (!AttachedElements.Contains(element))
{
AttachedElements.Add(element);
element.PointerEntered += Element_PointerEntered;
element.PointerExited += Element_PointerExited;
}
}
}
public static CoreCursorType GetUse(DependencyObject element)
{
return (CoreCursorType)element.GetValue(UseProperty);
}
private static void Element_PointerEntered(object sender, PointerRoutedEventArgs e)
{
CoreCursorType cursor = GetUse((DependencyObject)sender);
Window.Current.CoreWindow.PointerCursor = Cursors[cursor];
}
private static void Element_PointerExited(object sender, PointerRoutedEventArgs e)
{
Window.Current.CoreWindow.PointerCursor = DefaultCursor;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment