Skip to content

Instantly share code, notes, and snippets.

@lyahdav
Last active September 15, 2020 19:06
Show Gist options
  • Save lyahdav/8531e61a159dd1f542c64eb23c78dc17 to your computer and use it in GitHub Desktop.
Save lyahdav/8531e61a159dd1f542c64eb23c78dc17 to your computer and use it in GitHub Desktop.
C# FocusZone
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.System;
using Windows.UI.Core;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
// The Blank Page item template is documented at https://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409
namespace App1
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
}
async void OnKeyDown(object sender, KeyRoutedEventArgs e)
{
var isShiftDown = CoreWindow.GetForCurrentThread().GetKeyState(VirtualKey.Shift).HasFlag(CoreVirtualKeyStates.Down);
if (e.Key == Windows.System.VirtualKey.Up)
{
var isFirstControlFocused = FocusManager.FindFirstFocusableElement((DependencyObject)sender) == FocusManager.GetFocusedElement();
if (!isFirstControlFocused)
{
FocusManager.TryMoveFocus(FocusNavigationDirection.Previous);
e.Handled = true;
}
}
else if (e.Key == Windows.System.VirtualKey.Down)
{
var isLastControlFocused = FocusManager.FindLastFocusableElement((DependencyObject)sender) == FocusManager.GetFocusedElement();
if (!isLastControlFocused)
{
FocusManager.TryMoveFocus(FocusNavigationDirection.Next);
e.Handled = true;
}
} else if (e.Key == Windows.System.VirtualKey.Tab)
{
var options = new FindNextElementOptions()
{
ExclusionRect = LayoutInformation.GetLayoutSlot((FrameworkElement)sender),
};
var result = FocusManager.FindNextElement(isShiftDown ? FocusNavigationDirection.Up : FocusNavigationDirection.Down, options);
await FocusManager.TryFocusAsync(result, FocusState.Programmatic);
e.Handled = true;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment