test(a11y): run the WPF fixes on real WPF-UI controls; Restore down

SonarCloud's gate asks for 80% coverage on new code, and the first push had
22.5%: most of the new code only runs inside WPF. New tests run it on an STA
thread against WPF-UI's own styles and templates, with no window shown: the
names given to template parts, the glyphs kept out of the automation tree,
the decorative peers, the Ctrl+Q scope, the screen-reader notification, and
the font and contrast resources. A WPF-UI update that renames one of those
parts now fails a test instead of silently undoing the fix.

The seams for that: WpfUiAccessibility.Apply (what the class handlers run),
ScreenReader.Raise and RaiseOnActiveWindow, FontScaleService taking its
text-size reader and the resources it writes, ThemeService.ApplyDimming
taking the resources.

The tests also showed that WPF-UI 4.3 has a single button for Maximize and
Restore down, drawn as Restore down while the window is maximized; its name
now follows.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
poli0981andClaude Opus 5.5 committed 2026-11-16 10:33:45 +07:00
1 parent 79670fbe6f
commit 36bc62d7ba
9 files changed
+601 -64

No files matched your search

+3 -1
View File
@@ -97,7 +97,9 @@ documents — the user guide, this page, the legal texts — are in English.
items of a list are named by what they show, not by a program type; every page title is a
heading; the app declares that it follows each screen's scaling; no colour is written into a
screen; every icon is kept out of a screen reader's way; this page's links work and it never
claims conformance. The key every name uses must exist in all five languages.
claims conformance. The key every name uses must exist in all five languages. Other tests run the
fixes on real controls of the WPF-UI library the app is built with, so a library update that
renames one of their parts is caught before a release.
- **By an automated scan**: Axe.Windows, Microsoft's UI Automation rules (the engine of Accessibility
Insights for Windows), over every page of the running app, the first-start terms and the console
after a command, in the light and the dark theme and at Windows' largest Text size. Version 2.2.0
+2 -1
View File
@@ -44,7 +44,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
Run again; the catalog's splitters move with the arrow keys; every window and dialog starts with
the keyboard inside it, and a Caution confirmation on Cancel.
- **Unnamed controls** got names: the navigation pane's toggle and its two lists, the title bar's
buttons, a search box's clear button, the Settings cards and expanders, the Debug panel's tabs and
buttons (Maximize is read as Restore down while the window is maximized), a search box's clear
button, the Settings cards and expanders, the Debug panel's tabs and
the four "Read on GitHub" links; the Dangerous confirmation also reads the command's ID, and
Settings' theme and font size choices are read as groups. The log level list is translated.
- **Icons are no longer read** as stray symbols: they only decorate the word beside them, so a
@@ -22,9 +22,22 @@ namespace CommandForge.Desktop.Behaviors;
/// </summary>
public static class WpfUiAccessibility
{
/// <summary>The controls <see cref="Apply"/> fixes.</summary>
private static readonly Type[] HandledTypes =
[
typeof(NavigationView), typeof(TitleBar), typeof(Wpf.Ui.Controls.TextBox), typeof(CardExpander),
typeof(NavigationViewItem), typeof(CheckBox), typeof(InfoBar),
];
private static bool _registered;
/// <summary>Registers the handlers for every window the app opens. Call once, before the first window.</summary>
/// <summary>
/// Registers the handlers for every window the app opens. Call once, before the first window.
/// <see cref="Apply"/> runs when one of the controls loads and whenever its size changes. Loaded
/// alone is not enough: WPF raises it only on elements that have a Loaded handler of their own, and
/// some WPF-UI controls (CardExpander) have none, so a class handler never hears it. SizeChanged is
/// raised on every element after its first layout, when its template is applied.
/// </summary>
public static void Register()
{
if (_registered)
@@ -33,40 +46,47 @@ public static class WpfUiAccessibility
}
_registered = true;
Handle<NavigationView>(NameNavigationParts);
Handle<TitleBar>(control =>
var handler = new RoutedEventHandler((sender, _) => Apply(sender));
foreach (var type in HandledTypes)
{
NamePart(control, "PART_MinimizeButton", "A11y_Minimize");
NamePart(control, "PART_MaximizeButton", "A11y_Maximize");
NamePart(control, "PART_RestoreButton", "A11y_Restore");
NamePart(control, "PART_CloseButton", "A11y_Close");
});
Handle<Wpf.Ui.Controls.TextBox>(control => NamePart(control, "ClearButton", "A11y_ClearText"));
Handle<CardExpander>(NameExpanderHeader);
Handle<NavigationViewItem>(item => HideGlyph(item, "ChevronIcon"));
Handle<CheckBox>(box => HideGlyph(box, "ControlIcon"));
Handle<InfoBar>(NameSeverityIcon);
EventManager.RegisterClassHandler(type, FrameworkElement.LoadedEvent, handler);
EventManager.RegisterClassHandler(type, FrameworkElement.SizeChangedEvent, handler);
}
}
/// <summary>
/// Runs <paramref name="apply"/> when a control loads and whenever its size changes. Loaded alone is
/// not enough: WPF raises it only on elements that have a Loaded handler of their own, and some WPF-UI
/// controls (CardExpander) have none, so a class handler never hears it. SizeChanged is raised on every
/// element after its first layout, when its template is applied. Each step of <paramref name="apply"/>
/// does nothing when the part is already named.
/// Names the parts of <paramref name="element"/>'s template, or keeps its glyph out of the
/// automation tree, when it is one of the WPF-UI controls this class fixes; does nothing for
/// anything else, or for a part already fixed. Its template must be applied (it is by layout).
/// </summary>
private static void Handle<TControl>(Action<TControl> apply)
where TControl : Control
public static void Apply(object? element)
{
var handler = new RoutedEventHandler((sender, _) =>
switch (element)
{
if (sender is TControl control)
{
apply(control);
}
});
EventManager.RegisterClassHandler(typeof(TControl), FrameworkElement.LoadedEvent, handler);
EventManager.RegisterClassHandler(typeof(TControl), FrameworkElement.SizeChangedEvent, handler);
case NavigationView navigation:
NameNavigationParts(navigation);
break;
case TitleBar titleBar:
NamePart(titleBar, "PART_MinimizeButton", "A11y_Minimize");
NameMaximizeButton(titleBar);
NamePart(titleBar, "PART_CloseButton", "A11y_Close");
break;
case Wpf.Ui.Controls.TextBox textBox:
NamePart(textBox, "ClearButton", "A11y_ClearText");
break;
case CardExpander expander:
NameExpanderHeader(expander);
break;
case NavigationViewItem item:
HideGlyph(item, "ChevronIcon");
break;
case CheckBox box:
HideGlyph(box, "ControlIcon");
break;
case InfoBar bar:
NameSeverityIcon(bar);
break;
}
}
private static void NameNavigationParts(NavigationView navigation)
@@ -97,6 +117,22 @@ public static class WpfUiAccessibility
}
}
/// <summary>
/// WPF-UI has one button for Maximize and Restore down: it draws Restore while the window is
/// maximized, and its name follows.
/// </summary>
private static void NameMaximizeButton(TitleBar titleBar)
{
if (FindPart(titleBar, "PART_MaximizeButton") is { } button && !BindingOperations.IsDataBound(button, AutomationProperties.NameProperty))
{
var name = new MultiBinding { Converter = MaximizeNameConverter.Instance };
name.Bindings.Add(new Binding(nameof(TitleBar.IsMaximized)) { Source = titleBar });
name.Bindings.Add(LocalizationManager.Bind("A11y_Maximize"));
name.Bindings.Add(LocalizationManager.Bind("A11y_Restore"));
button.SetBinding(AutomationProperties.NameProperty, name);
}
}
/// <summary>The header toggle speaks the expander's own name (set in XAML), so "Logs size, expanded".</summary>
private static void NameExpanderHeader(CardExpander expander)
{
@@ -166,6 +202,25 @@ public static class WpfUiAccessibility
return control.Template?.FindName(partName, control) as FrameworkElement;
}
/// <summary>The values: whether the window is maximized; the translated Maximize and Restore down.</summary>
private sealed class MaximizeNameConverter : IMultiValueConverter
{
public static readonly MaximizeNameConverter Instance = new();
public object Convert(object[] values, Type targetType, object? parameter, CultureInfo culture)
{
if (values is not [bool maximized, string maximize, string restore])
{
return string.Empty;
}
return maximized ? restore : maximize;
}
public object[] ConvertBack(object value, Type[] targetTypes, object? parameter, CultureInfo culture)
=> throw new NotSupportedException();
}
/// <summary>
/// The values: the bar's <see cref="InfoBarSeverity"/>; the translated names of information,
/// success, warning and error; the pattern; the bar's title and message.
+26 -9
View File
@@ -28,34 +28,51 @@ public static class ScreenReader
return;
}
app.Dispatcher.InvokeAsync(() => Raise(app, message, important));
app.Dispatcher.InvokeAsync(() => RaiseOnActiveWindow(app.Windows.OfType<Window>(), app.MainWindow, message, important));
}
private static void Raise(System.Windows.Application app, string message, bool important)
/// <summary>
/// When a screen reader listens, raises the notification on the active window of
/// <paramref name="windows"/>, else on <paramref name="mainWindow"/>. False when nothing was raised.
/// </summary>
public static bool RaiseOnActiveWindow(IEnumerable<Window> windows, Window? mainWindow, string message, bool important)
{
if (!AutomationPeer.ListenerExists(AutomationEvents.Notification))
{
return;
}
ArgumentNullException.ThrowIfNull(windows);
return AutomationPeer.ListenerExists(AutomationEvents.Notification)
&& Raise(windows.FirstOrDefault(w => w.IsActive) ?? mainWindow, message, important);
}
var window = app.Windows.OfType<Window>().FirstOrDefault(w => w.IsActive) ?? app.MainWindow;
/// <summary>
/// Raises the notification on <paramref name="window"/>'s automation peer, on its thread. False when
/// there is no window or no peer, or UI Automation refused it.
/// </summary>
public static bool Raise(Window? window, string message, bool important)
{
ArgumentException.ThrowIfNullOrWhiteSpace(message);
if (window is null)
{
return;
return false;
}
try
{
var peer = UIElementAutomationPeer.FromElement(window) ?? UIElementAutomationPeer.CreatePeerForElement(window);
peer?.RaiseNotificationEvent(
if (peer is null)
{
return false;
}
peer.RaiseNotificationEvent(
important ? AutomationNotificationKind.ActionCompleted : AutomationNotificationKind.Other,
important ? AutomationNotificationProcessing.ImportantMostRecent : AutomationNotificationProcessing.MostRecent,
message,
ActivityId);
return true;
}
catch (Exception ex) when (ex is InvalidOperationException or NotSupportedException)
{
Log.Debug(ex, "Could not raise a screen-reader notification.");
return false;
}
}
}
@@ -1,3 +1,4 @@
using System.Windows;
using CommandForge.Application.Settings;
using Microsoft.Win32;
@@ -21,19 +22,55 @@ public sealed class FontScaleService : IFontScaleService, IDisposable
private const double PaneWidth = 290;
private readonly Func<double> _readTextScale;
private readonly Func<ResourceDictionary?> _resources;
private FontScale _scale = FontScale.Medium;
private double _textScale = WindowsTextScale.Minimum;
private bool _subscribed;
/// <summary>Rewrites the application's resources, with Windows' own Text size.</summary>
public FontScaleService()
: this(WindowsTextScale.Read, static () => System.Windows.Application.Current?.Resources)
{
}
/// <summary>
/// Rewrites the resources <paramref name="resources"/> returns (none: nothing to do), with the text
/// size factor <paramref name="readTextScale"/> returns.
/// </summary>
public FontScaleService(Func<double> readTextScale, Func<ResourceDictionary?> resources)
{
ArgumentNullException.ThrowIfNull(readTextScale);
ArgumentNullException.ThrowIfNull(resources);
_readTextScale = readTextScale;
_resources = resources;
}
/// <inheritdoc />
public void Apply(FontScale scale)
{
_scale = scale;
_textScale = WindowsTextScale.Read();
_textScale = _readTextScale();
Subscribe();
ApplyResources();
}
/// <summary>
/// Re-reads Windows' text size and rescales only when it changed: when Windows reports a
/// preference change, and when the app comes back to the foreground.
/// </summary>
public void Refresh()
{
var factor = _readTextScale();
if (Math.Abs(factor - _textScale) < 0.001)
{
return;
}
_textScale = factor;
ApplyResources();
}
/// <inheritdoc />
public void Dispose() => Unsubscribe();
@@ -60,13 +97,12 @@ public sealed class FontScaleService : IFontScaleService, IDisposable
private void ApplyResources()
{
if (System.Windows.Application.Current is not { } app)
if (_resources() is not { } resources)
{
return;
}
var body = BodySize(_scale, _textScale);
var resources = app.Resources;
resources[ResourceKey] = body;
resources["ControlContentThemeFontSize"] = body;
resources["AppFontSizeCaption"] = body - 2;
@@ -76,19 +112,6 @@ public sealed class FontScaleService : IFontScaleService, IDisposable
resources[PaneWidthKey] = NavigationPaneWidth(body);
}
/// <summary>Re-reads Windows' text size and rescales only when it changed.</summary>
private void Refresh()
{
var factor = WindowsTextScale.Read();
if (Math.Abs(factor - _textScale) < 0.001)
{
return;
}
_textScale = factor;
ApplyResources();
}
private void Subscribe()
{
if (_subscribed || System.Windows.Application.Current is not { } app)
+8 -9
View File
@@ -34,7 +34,10 @@ public sealed class ThemeService : IThemeService, IDisposable
updateAccent: true);
}
ApplyDimming(SystemParameters.HighContrast);
if (System.Windows.Application.Current is { } app)
{
ApplyDimming(app.Resources, SystemParameters.HighContrast);
}
// Keep listening in every mode: High Contrast can be switched on while the app runs.
Subscribe();
@@ -44,15 +47,11 @@ public sealed class ThemeService : IThemeService, IDisposable
/// Dimmed text (list descriptions) and badge icons blend the colors under them, which a Windows
/// contrast theme forbids: there they are drawn at full strength (see AppStyles.xaml).
/// </summary>
private static void ApplyDimming(bool highContrast)
public static void ApplyDimming(ResourceDictionary resources, bool highContrast)
{
if (System.Windows.Application.Current is not { } app)
{
return;
}
app.Resources["AppDimOpacity"] = highContrast ? 1d : 0.78d;
app.Resources["AppBadgeOpacity"] = highContrast ? 1d : 0.75d;
ArgumentNullException.ThrowIfNull(resources);
resources["AppDimOpacity"] = highContrast ? 1d : 0.78d;
resources["AppBadgeOpacity"] = highContrast ? 1d : 0.75d;
}
/// <inheritdoc />
@@ -168,4 +168,142 @@ public sealed class AccessibilityHelpersTests
Assert.Equal("Warning: Not vetted.", WpfUiAccessibility.InfoBarText("Warning", "{0}: {1}", "Not vetted.", string.Empty));
Assert.Equal("Information", WpfUiAccessibility.InfoBarText("Information", "{0}: {1}", null, " "));
}
[Fact]
public void TheFontSizesFollowTheChoiceAndWindowsTextSize()
{
var resources = new ResourceDictionary();
var textScale = 1d;
using var fonts = new FontScaleService(() => textScale, () => resources);
fonts.Apply(FontScale.Large);
Assert.Equal(16d, resources[FontScaleService.ResourceKey]);
Assert.Equal(16d, resources["ControlContentThemeFontSize"]);
Assert.Equal(14d, resources["AppFontSizeCaption"]);
Assert.Equal(32d, resources["AppFontSizeTitle"]);
Assert.Equal(290d, resources[FontScaleService.PaneWidthKey]);
// Windows' Text size changes while the app runs: re-read when the app is back in front.
textScale = 2.25;
fonts.Refresh();
Assert.Equal(36d, resources[FontScaleService.ResourceKey]);
Assert.Equal(497d, resources[FontScaleService.PaneWidthKey]);
// Unchanged: nothing is rewritten.
resources.Clear();
fonts.Refresh();
Assert.False(resources.Contains(FontScaleService.ResourceKey));
}
[Fact]
public void WithoutResourcesTheFontSizesAreLeftAlone()
{
using var fonts = new FontScaleService(() => 1.5, () => null);
using var defaults = new FontScaleService(); // the app's resources: none in a test
fonts.Apply(FontScale.Small);
fonts.Refresh();
defaults.Apply(FontScale.Medium);
defaults.Refresh();
Assert.Throws<ArgumentNullException>(() => new FontScaleService(null!, () => null));
Assert.Throws<ArgumentNullException>(() => new FontScaleService(() => 1, null!));
}
[Fact]
public void WindowsTextSizeIsReadAsAFactorTheAppSupports()
=> Assert.InRange(WindowsTextScale.Read(), WindowsTextScale.Minimum, 2.25);
[Fact]
public void AContrastThemeDrawsDimmedTextAtFullStrength()
{
var resources = new ResourceDictionary();
ThemeService.ApplyDimming(resources, highContrast: true);
Assert.Equal(1d, resources["AppDimOpacity"]);
Assert.Equal(1d, resources["AppBadgeOpacity"]);
ThemeService.ApplyDimming(resources, highContrast: false);
Assert.Equal(0.78d, resources["AppDimOpacity"]);
Assert.Equal(0.75d, resources["AppBadgeOpacity"]);
Assert.Throws<ArgumentNullException>(() => ThemeService.ApplyDimming(null!, highContrast: true));
}
[Fact]
public void ALocalizedBindingFollowsTheLanguage()
{
var binding = LocalizationManager.Bind("A11y_Close");
Assert.Equal("[A11y_Close]", binding.Path.Path);
Assert.Same(LocalizationManager.Instance, binding.Source);
Assert.Equal(System.Windows.Data.BindingMode.OneWay, binding.Mode);
}
[Fact]
public void ACommandRowsStatusIsRaisedWhenItChanges()
{
var command = new CommandDefinition
{
Id = "t.tweak",
CategoryId = "c",
TitleKey = "A11y_Close",
DescriptionKey = "A11y_Close",
Executable = "x",
DangerLevel = DangerLevel.Caution,
RequiresAdmin = true,
RevertCommandId = "t.tweak.undo",
};
var row = new CommandItemViewModel(command, "Tweak", "A tweak.");
var changed = new List<string?>();
row.PropertyChanged += (_, e) => changed.Add(e.PropertyName);
Assert.Equal(CommandItemViewModel.StatusText(DangerLevel.Caution, true, false, true, false), row.AccessibleStatus);
Assert.Contains(Strings.Get("A11y_CanUndo"), row.AccessibleStatus, StringComparison.Ordinal);
row.IsFavorite = true;
Assert.Contains(nameof(CommandItemViewModel.AccessibleStatus), changed);
Assert.Contains(Strings.Get("A11y_Favorite"), row.AccessibleStatus, StringComparison.Ordinal);
changed.Clear();
row.Refresh();
Assert.Contains(nameof(CommandItemViewModel.AccessibleStatus), changed);
}
[Fact]
public void ANotificationIsShownAndReadOrOnlyRead()
{
// No application in a test: nothing is shown or said, and nothing fails.
var notifications = new SnackbarNotificationService(new Wpf.Ui.SnackbarService());
notifications.Show("Saved to C:\\Temp\\output.txt", NotificationKind.Success);
notifications.Show("Cancelled", NotificationKind.Warning, announce: false);
notifications.Announce("System uptime: Success", important: true);
Assert.Throws<ArgumentNullException>(() => notifications.Announce(null!));
}
[Fact]
public void TheConvertersAreOneWayAndTheirOwnMarkup()
{
var format = new FormatConverter();
var level = new LogLevelToTextConverter();
var blank = new BlankToBooleanConverter();
var rowAction = new RowActionNameConverter { LabelKey = "Favorite_Add" };
Assert.Same(format, format.ProvideValue(null!));
Assert.Same(level, level.ProvideValue(null!));
Assert.Same(blank, blank.ProvideValue(null!));
Assert.Throws<NotSupportedException>(() => format.ConvertBack("x", [typeof(string)], null, CultureInfo.InvariantCulture));
Assert.Throws<NotSupportedException>(() => level.ConvertBack("x", typeof(LogLevel), null, CultureInfo.InvariantCulture));
Assert.Throws<NotSupportedException>(() => blank.ConvertBack(true, typeof(string), null, CultureInfo.InvariantCulture));
Assert.Throws<NotSupportedException>(() => rowAction.ConvertBack("x", typeof(string), null, CultureInfo.InvariantCulture));
Assert.Equal(LogLevelToTextConverter.Text(LogLevel.Warning), level.Convert(LogLevel.Warning, typeof(string), null, CultureInfo.InvariantCulture));
Assert.Equal(Strings.Get("LogLevel_Error"), LogLevelToTextConverter.Text(LogLevel.Fatal));
Assert.Equal(string.Empty, level.Convert("Warning", typeof(string), null, CultureInfo.InvariantCulture));
Assert.Equal(
RowActionNameConverter.Format(Strings.Get("Favorite_Add"), "Flush DNS cache"),
rowAction.Convert("Flush DNS cache", typeof(string), null, CultureInfo.InvariantCulture));
Assert.Equal(Strings.Get("Favorite_Add"), rowAction.Convert(null, typeof(string), null, CultureInfo.InvariantCulture));
}
}
+36
View File
@@ -0,0 +1,36 @@
using System.Runtime.ExceptionServices;
using System.Windows.Threading;
namespace CommandForge.Tests;
/// <summary>
/// Runs a test's body on a thread of its own in a single-threaded apartment, where WPF elements can
/// be created, and rethrows what it threw. No window is shown.
/// </summary>
internal static class Sta
{
public static void Run(Action body)
{
ArgumentNullException.ThrowIfNull(body);
ExceptionDispatchInfo? failure = null;
var thread = new Thread(() =>
{
try
{
body();
}
catch (Exception ex)
{
failure = ExceptionDispatchInfo.Capture(ex);
}
finally
{
Dispatcher.CurrentDispatcher.InvokeShutdown();
}
});
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
thread.Join();
failure?.Throw();
}
}
@@ -0,0 +1,266 @@
using System.Windows;
using System.Windows.Automation;
using System.Windows.Automation.Peers;
using System.Windows.Controls;
using System.Windows.Media;
using CommandForge.Desktop.Behaviors;
using CommandForge.Desktop.Controls;
using CommandForge.Desktop.Resources;
using CommandForge.Desktop.Services;
using Wpf.Ui.Appearance;
using Wpf.Ui.Controls;
using Wpf.Ui.Markup;
using TextBlock = System.Windows.Controls.TextBlock;
using TextBox = System.Windows.Controls.TextBox;
namespace CommandForge.Tests;
/// <summary>
/// The accessibility fixes that live in WPF itself, run on real controls with WPF-UI's own styles
/// and templates (on an STA thread, no window shown): the names given to WPF-UI's template parts,
/// the glyphs kept out of the automation tree, the decorative peers, the Ctrl+Q scope and the
/// screen-reader notification. A WPF-UI update that renames a template part fails here.
/// </summary>
public sealed class WpfAccessibilityRuntimeTests
{
[Fact]
public void TheNavigationPanesToggleAndListsAreNamedAndItsFrameIsNoTabStop() => Sta.Run(() =>
{
var navigation = new NavigationView { PaneDisplayMode = NavigationViewPaneDisplayMode.Left };
Host(navigation);
WpfUiAccessibility.Apply(navigation);
Assert.Equal(Strings.Get("MenuToggleSidebar"), NameOf(Part(navigation, "PART_ToggleButton")));
Assert.Equal(Strings.Get("MenuToggleSidebar"), Part(navigation, "PART_ToggleButton").ToolTip);
Assert.Equal(Strings.Get("A11y_NavigationPages"), NameOf(Part(navigation, "PART_MenuItemsItemsControl")));
Assert.Equal(Strings.Get("A11y_NavigationFooter"), NameOf(Part(navigation, "PART_FooterMenuItemsItemsControl")));
Assert.False(Part(navigation, "PART_NavigationViewContentPresenter").Focusable);
});
[Fact]
public void TheTitleBarsCaptionButtonsAreNamed() => Sta.Run(() =>
{
var titleBar = new TitleBar();
Host(titleBar);
WpfUiAccessibility.Apply(titleBar);
Assert.Equal(Strings.Get("A11y_Minimize"), NameOf(Part(titleBar, "PART_MinimizeButton")));
Assert.Equal(Strings.Get("A11y_Maximize"), NameOf(Part(titleBar, "PART_MaximizeButton")));
Assert.Equal(Strings.Get("A11y_Close"), NameOf(Part(titleBar, "PART_CloseButton")));
// One button for both: it draws Restore down while the window is maximized.
titleBar.SetValue(TitleBar.IsMaximizedProperty, true);
Assert.Equal(Strings.Get("A11y_Restore"), NameOf(Part(titleBar, "PART_MaximizeButton")));
});
[Fact]
public void ATextBoxsClearButtonIsNamedOnce() => Sta.Run(() =>
{
var box = new Wpf.Ui.Controls.TextBox { ClearButtonEnabled = true, Text = "uptime" };
Host(box);
WpfUiAccessibility.Apply(box);
WpfUiAccessibility.Apply(box);
Assert.Equal(Strings.Get("A11y_ClearText"), NameOf(Part(box, "ClearButton")));
});
[Fact]
public void ACardExpandersHeaderSpeaksTheExpandersName() => Sta.Run(() =>
{
var expander = new CardExpander { Header = new StackPanel() };
AutomationProperties.SetName(expander, "Log size:");
Host(expander);
WpfUiAccessibility.Apply(expander);
WpfUiAccessibility.Apply(expander);
Assert.Equal("Log size:", NameOf(Part(expander, "ExpanderToggleButton")));
});
[Fact]
public void ACheckBoxsTickAndANavigationItemsArrowAreLeftOutOfTheTree() => Sta.Run(() =>
{
var box = new CheckBox { Content = "Auto-scroll", IsChecked = true };
var item = new NavigationViewItem { Content = "Command catalog" };
item.MenuItems.Add(new NavigationViewItem { Content = "Network" });
// A navigation item gets its template from the navigation view it is in, as in the app.
var navigation = new NavigationView { PaneDisplayMode = NavigationViewPaneDisplayMode.Left };
navigation.MenuItems.Add(item);
Host(new StackPanel { Children = { box, navigation } });
WpfUiAccessibility.Apply(box);
WpfUiAccessibility.Apply(item);
WpfUiAccessibility.Apply(item);
foreach (var (control, part) in new (Control, string)[] { (box, "ControlIcon"), (item, "ChevronIcon") })
{
var icon = Part(control, part);
Assert.IsType<GlyphHost>(Assert.Single(((Panel)VisualTreeHelper.GetChild(icon, 0)).Children));
Assert.DoesNotContain(TextsIn(UIElementAutomationPeer.CreatePeerForElement(control)), IsGlyph);
}
});
[Fact]
public void AnInfoBarIsReadThroughItsSeverityIcon() => Sta.Run(() =>
{
var bar = new InfoBar { Title = "Not vetted.", Message = "Runs as you.", Severity = InfoBarSeverity.Warning, IsOpen = true };
Host(bar);
WpfUiAccessibility.Apply(bar);
WpfUiAccessibility.Apply(bar);
// WPF-UI draws the glyph with its own TextBlock, a subclass of WPF's.
var glyph = Assert.IsType<TextBlock>(Assert.Single(((Panel)VisualTreeHelper.GetChild(Part(bar, "SymbolIcon"), 0)).Children), exactMatch: false);
var pattern = Strings.Get("A11y_InfoBar");
Assert.Equal(WpfUiAccessibility.InfoBarText(Strings.Get("A11y_SeverityWarning"), pattern, "Not vetted.", "Runs as you."), NameOf(glyph));
bar.Severity = InfoBarSeverity.Error;
Assert.Equal(WpfUiAccessibility.InfoBarText(Strings.Get("A11y_SeverityError"), pattern, "Not vetted.", "Runs as you."), NameOf(glyph));
bar.Severity = InfoBarSeverity.Success;
Assert.Equal(WpfUiAccessibility.InfoBarText(Strings.Get("A11y_SeveritySuccess"), pattern, "Not vetted.", "Runs as you."), NameOf(glyph));
bar.Severity = InfoBarSeverity.Informational;
Assert.Equal(WpfUiAccessibility.InfoBarText(Strings.Get("A11y_SeverityInfo"), pattern, "Not vetted.", "Runs as you."), NameOf(glyph));
});
[Fact]
public void OtherElementsAreLeftAlone() => Sta.Run(() =>
{
WpfUiAccessibility.Register();
WpfUiAccessibility.Register();
var button = new System.Windows.Controls.Button();
WpfUiAccessibility.Apply(button);
WpfUiAccessibility.Apply(null);
Assert.Equal(string.Empty, NameOf(button));
});
[Fact]
public void ADecorativeIconIsAnImageWithoutChildrenAndOutOfTheControlViewUntilNamed() => Sta.Run(() =>
{
var icon = new DecorativeIcon(SymbolRegular.Warning24, 16);
_ = new DecorativeIcon();
var peer = UIElementAutomationPeer.CreatePeerForElement(icon);
Assert.Null(peer.GetChildren());
Assert.Equal(AutomationControlType.Image, peer.GetAutomationControlType());
Assert.Equal(nameof(DecorativeIcon), peer.GetClassName());
Assert.False(peer.IsControlElement());
Assert.False(peer.IsContentElement());
// Named, it would be an image to read: still not in the control view while it is not shown.
AutomationProperties.SetName(icon, "Warning");
Assert.Equal("Warning", peer.GetName());
Assert.False(peer.IsControlElement());
Assert.False(peer.IsContentElement());
});
[Fact]
public void AGlyphHostHidesTheGlyphItHolds() => Sta.Run(() =>
{
var host = new GlyphHost { Child = new TextBlock { Text = "" } };
var peer = UIElementAutomationPeer.CreatePeerForElement(host);
Assert.Null(peer.GetChildren());
Assert.Equal(nameof(GlyphHost), peer.GetClassName());
Assert.False(peer.IsControlElement());
});
[Fact]
public void ALabeledGroupIsAGroup() => Sta.Run(() =>
{
var peer = UIElementAutomationPeer.CreatePeerForElement(new LabeledGroup());
Assert.Equal(AutomationControlType.Group, peer.GetAutomationControlType());
Assert.Equal(nameof(LabeledGroup), peer.GetClassName());
});
[Fact]
public void CtrlQWaitsWhileTextIsBeingEdited() => Sta.Run(() =>
{
var editing = new TextBox();
var readOnly = new TextBox { IsReadOnly = true };
var search = new TextBox();
ShortcutScope.SetAllowExit(search, true);
Assert.True(ShortcutScope.CanExitFrom(null));
Assert.True(ShortcutScope.CanExitFrom(new System.Windows.Controls.Button()));
Assert.False(ShortcutScope.CanExitFrom(editing));
Assert.True(ShortcutScope.CanExitFrom(readOnly));
Assert.True(ShortcutScope.CanExitFrom(search));
Assert.True(ShortcutScope.GetAllowExit(search));
Assert.Throws<ArgumentNullException>(() => ShortcutScope.GetAllowExit(null!));
Assert.Throws<ArgumentNullException>(() => ShortcutScope.SetAllowExit(null!, true));
});
[Fact]
public void AnEditableComboBoxsTextBoxAnswersForItsComboBox() => Sta.Run(() =>
{
var combo = new ComboBox { IsEditable = true };
Host(combo);
var inner = Assert.IsType<TextBox>(combo.Template.FindName("PART_EditableTextBox", combo), exactMatch: false);
Assert.False(ShortcutScope.CanExitFrom(inner));
ShortcutScope.SetAllowExit(combo, true);
Assert.True(ShortcutScope.CanExitFrom(inner));
});
[Fact]
public void ANotificationIsRaisedOnTheWindowsPeer() => Sta.Run(() =>
{
// No application in a test: announcing is a no-op, never an error.
ScreenReader.Announce(null);
ScreenReader.Announce(" ");
ScreenReader.Announce("Running System uptime");
Assert.False(ScreenReader.Raise(null, "Running System uptime", important: false));
Assert.True(ScreenReader.Raise(new Window(), "System uptime: Success", important: true));
Assert.True(ScreenReader.Raise(new Window(), "3 commands found", important: false));
Assert.Throws<ArgumentException>(() => ScreenReader.Raise(new Window(), " ", important: false));
// Whether a screen reader listens depends on the PC; either way nothing fails.
_ = ScreenReader.RaiseOnActiveWindow([new Window()], new Window(), "Waiting for administrator permission", important: false);
Assert.Throws<ArgumentNullException>(() => ScreenReader.RaiseOnActiveWindow(null!, null, "x", important: false));
});
/// <summary>Lays <paramref name="content"/> out under WPF-UI's styles, as App.xaml merges them.</summary>
private static void Host(UIElement content)
{
_ = System.Windows.Application.Current; // registers the pack://application: resources
var root = new Border { Width = 900, Height = 700 };
root.Resources.MergedDictionaries.Add(new ThemesDictionary { Theme = ApplicationTheme.Light });
root.Resources.MergedDictionaries.Add(new ControlsDictionary());
root.Child = content;
root.Measure(new Size(900, 700));
root.Arrange(new Rect(0, 0, 900, 700));
root.UpdateLayout();
}
private static FrameworkElement Part(Control control, string name)
=> Assert.IsAssignableFrom<FrameworkElement>(control.Template?.FindName(name, control));
private static string NameOf(DependencyObject element) => AutomationProperties.GetName(element);
private static IEnumerable<string> TextsIn(AutomationPeer peer)
{
foreach (var child in peer.GetChildren() ?? [])
{
if (child.GetAutomationControlType() == AutomationControlType.Text)
{
yield return child.GetName();
}
foreach (var text in TextsIn(child))
{
yield return text;
}
}
}
// A character of the icon fonts' private-use range, which a screen reader can't say.
private static bool IsGlyph(string text) => text.Any(c => c is >= '' and <= '');
}