Skip to content
Merged
Prev Previous commit
Next Next commit
Add DialogHost.IsFocusRestoreDisabled DP to opt. disable focus restore
  • Loading branch information
nicolaihenriksen committed Feb 27, 2023
commit 64764d87fb263274dbf118645ef5017f11e1f31d
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
</UserControl.Resources>

<Grid>
<materialDesign:DialogHost x:Name="DialogHost">
<materialDesign:DialogHost x:Name="DialogHost" IsFocusRestoreDisabled="True">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
Expand Down
28 changes: 22 additions & 6 deletions MaterialDesignThemes.Wpf/DialogHost.cs
Original file line number Diff line number Diff line change
Expand Up @@ -367,13 +367,16 @@ private static void IsOpenPropertyChangedCallback(DependencyObject dependencyObj

dialogHost.CurrentSession = new DialogSession(dialogHost);
var window = Window.GetWindow(dialogHost);
dialogHost._restoreFocusDialogClose = window != null ? FocusManager.GetFocusedElement(window) : null;

// Check restore focus overrides and optional disabling
if (dialogHost._restoreFocusDialogClose is DependencyObject dependencyObj &&
GetRestoreFocusElement(dependencyObj) is { } focusOverride)
if (!dialogHost.IsFocusRestoreDisabled)
{
dialogHost._restoreFocusDialogClose = focusOverride;
dialogHost._restoreFocusDialogClose = window != null ? FocusManager.GetFocusedElement(window) : null;

// Check restore focus overrides
if (dialogHost._restoreFocusDialogClose is DependencyObject dependencyObj &&
GetRestoreFocusElement(dependencyObj) is { } focusOverride)
{
dialogHost._restoreFocusDialogClose = focusOverride;
}
}

//multiple ways of calling back that the dialog has opened:
Expand Down Expand Up @@ -609,6 +612,8 @@ public override void OnApplyTemplate()
base.OnApplyTemplate();
}

#region focus restore properties

public static readonly DependencyProperty RestoreFocusElementProperty = DependencyProperty.RegisterAttached(
"RestoreFocusElement", typeof(IInputElement), typeof(DialogHost), new PropertyMetadata(default(IInputElement)));

Expand All @@ -618,6 +623,17 @@ public static void SetRestoreFocusElement(DependencyObject element, IInputElemen
public static IInputElement GetRestoreFocusElement(DependencyObject element)
=> (IInputElement) element.GetValue(RestoreFocusElementProperty);

public static readonly DependencyProperty IsFocusRestoreDisabledProperty = DependencyProperty.Register(
nameof(IsFocusRestoreDisabled), typeof(bool), typeof(DialogHost), new PropertyMetadata(false));

public bool IsFocusRestoreDisabled
{
get => (bool) GetValue(IsFocusRestoreDisabledProperty);
set => SetValue(IsFocusRestoreDisabledProperty, value);
}

#endregion

#region open dialog events/callbacks

public static readonly RoutedEvent DialogOpenedEvent =
Expand Down