Skip to content

Commit

Permalink
Ensured the search box is focused when the dialog is opened.
Browse files Browse the repository at this point in the history
  • Loading branch information
reduckted committed Mar 23, 2021
1 parent a359565 commit c8d0363
Show file tree
Hide file tree
Showing 2 changed files with 73 additions and 1 deletion.
71 changes: 71 additions & 0 deletions source/ProjectFilter/UI/AttachedProperties/FocusWhenVisible.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
using Microsoft.VisualStudio;
using System;
using System.Windows;


namespace ProjectFilter.UI.AttachedProperties {

public static class FocusWhenVisible {

public static readonly DependencyProperty EnabledProperty = DependencyProperty.RegisterAttached(
"Enabled",
typeof(bool),
typeof(FocusWhenVisible),
new PropertyMetadata(false, OnEnabledChanged)
);


public static bool GetEnabled(DependencyObject obj) {
if (obj is null) {
throw new ArgumentNullException(nameof(obj));
}

return (bool)obj.GetValue(EnabledProperty);
}


public static void SetEnabled(DependencyObject obj, bool value) {
if (obj is null) {
throw new ArgumentNullException(nameof(obj));
}

obj.SetValue(EnabledProperty, value);
}


private static void OnEnabledChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) {
UIElement? target;


target = d as UIElement;

if (target != null) {
if ((bool)e.OldValue) {
target.IsVisibleChanged -= OnIsVisibleChanged;
}

if ((bool)e.NewValue) {
target.IsVisibleChanged += OnIsVisibleChanged;
}
}
}


private static void OnIsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e) {
UIElement? target;


target = sender as UIElement;

if (target != null && target.IsVisible) {
try {
target.Focus();
} catch (Exception ex) when (!ErrorHandler.IsCriticalException(ex)) {
System.Diagnostics.Debug.WriteLine(ex);
}
}
}

}

}
3 changes: 2 additions & 1 deletion source/ProjectFilter/UI/FilterDialog.xaml
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@
Foreground="{DynamicResource {x:Static platform:ThemedDialogColors.HeaderTextBrushKey}}"
/>
</Grid>

<Grid Visibility="{Binding LoadedVisibility}">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
Expand Down Expand Up @@ -130,6 +130,7 @@
Style="{StaticResource SearchTextBoxStyle}"
properties:Watermark.Text="Filter projects..."
properties:ClearOnEscape.Enabled="True"
properties:FocusWhenVisible.Enabled="True"
/>
</StackPanel>

Expand Down

0 comments on commit c8d0363

Please sign in to comment.