Skip to content

Commit

Permalink
fix: Flyout should return focus to previously focused
Browse files Browse the repository at this point in the history
  • Loading branch information
MartinZikmund committed Sep 3, 2021
1 parent bc8d7fa commit 4d8af83
Showing 1 changed file with 25 additions and 0 deletions.
25 changes: 25 additions & 0 deletions src/Uno.UI/UI/Xaml/Controls/Popup/PopupBase.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using System;
using Uno.UI;
using Uno.UI.Xaml.Core;
using Windows.Foundation;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
Expand All @@ -15,6 +16,9 @@ namespace Windows.UI.Xaml.Controls
{
public partial class PopupBase : FrameworkElement, IPopup
{
private WeakReference<UIElement> _lastFocusedElement = null;
private FocusState _lastFocusState = FocusState.Unfocused;

private IDisposable _openPopupRegistration;
private bool _childHasOwnDataContext;

Expand Down Expand Up @@ -62,11 +66,32 @@ partial void OnIsOpenChangedPartial(bool oldIsOpen, bool newIsOpen)
if (newIsOpen)
{
_openPopupRegistration = VisualTreeHelper.RegisterOpenPopup(this);

if (IsLightDismissEnabled)
{
// Store last focused element
var focusManager = VisualTree.GetFocusManagerForElement(this);
var focusedElement = focusManager.FocusedElement as UIElement;
var focusState = focusManager.GetRealFocusStateForFocusedElement();
if (focusedElement != null && focusState != FocusState.Unfocused)
{
_lastFocusedElement = new WeakReference<UIElement>(focusedElement);
_lastFocusState = focusState;
}
}

Opened?.Invoke(this, newIsOpen);
}
else
{
_openPopupRegistration?.Dispose();

if (_lastFocusedElement != null && _lastFocusedElement.TryGetTarget(out var target))
{
target.Focus(_lastFocusState);
_lastFocusedElement = null;
}

Closed?.Invoke(this, newIsOpen);
}
}
Expand Down

0 comments on commit 4d8af83

Please sign in to comment.