Skip to content

Commit cedea52

Browse files
TalwynoxKeboo
andauthored
Fix dialog focus (#3249)
* Add Handler to correctly focus dialog when it is vissible * Centralizing focus logic to remove duplication --------- Co-authored-by: Kevin Bost <[email protected]>
1 parent 7083fa5 commit cedea52

File tree

1 file changed

+28
-5
lines changed

1 file changed

+28
-5
lines changed

MaterialDesignThemes.Wpf/DialogHost.cs

Lines changed: 28 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -816,14 +816,37 @@ internal void InternalClose(object? parameter)
816816
if (child is null) return null;
817817

818818
CommandManager.InvalidateRequerySuggested();
819-
var focusable = child.VisualDepthFirstTraversal().OfType<UIElement>().FirstOrDefault(ui => ui.Focusable && ui.IsVisible);
820-
focusable?.Dispatcher.InvokeAsync(() =>
819+
var focusable = child.VisualDepthFirstTraversal().OfType<UIElement>().FirstOrDefault(ui => ui.Focusable);
820+
if (focusable is null) return null;
821+
822+
if (focusable.IsVisible)
823+
{
824+
MoveFocus(focusable);
825+
}
826+
else
821827
{
822-
if (!focusable.Focus()) return;
823-
focusable.MoveFocus(new TraversalRequest(FocusNavigationDirection.First));
824-
}, DispatcherPriority.Background);
828+
focusable.IsVisibleChanged += FocusableOnIsVisibleChanged;
829+
}
825830

826831
return child;
832+
833+
void FocusableOnIsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e)
834+
{
835+
if (sender is UIElement focusable)
836+
{
837+
MoveFocus(focusable);
838+
focusable.IsVisibleChanged -= FocusableOnIsVisibleChanged;
839+
}
840+
}
841+
842+
void MoveFocus(UIElement focusable)
843+
{
844+
focusable.Dispatcher.BeginInvoke(() =>
845+
{
846+
if (!focusable.Focus()) return;
847+
focusable.MoveFocus(new TraversalRequest(FocusNavigationDirection.First));
848+
}, DispatcherPriority.Background);
849+
}
827850
}
828851

829852
protected override void OnPreviewMouseDown(MouseButtonEventArgs e)

0 commit comments

Comments
 (0)