Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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