Created
July 18, 2017 14:07
-
-
Save martinsuchan/7f5511ec6a7fdb213979afe0766bab3f to your computer and use it in GitHub Desktop.
CoreCursor attached property helper class.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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