WPF: Setting the accessible name on an edit field

This article is referenced directly by Microsoft Accessibility Insights for Windows. Microsoft Accessibility Insights for Windows can help spotlight many accessibility issues in UI, and guide you to the relevant UI framework-specific code sample to help you resolve the issue. Learn more about Microsoft Accessibility Insights for Windows.

Problem

When a screen reader moves to the TextBox control, its announcement does not include the purpose of the TextBox. As such, my customer may be blocked from completing their task.

Suggested Fix

The purpose of a control is conveyed through the control's Name property as exposed through the UI Automation (UIA) API. The Name property must be accurate, concise, unambiguous and localized.

Note

With a WPF TextBlock control, the control's Text property is repurposed as the UIA Name property. This is not the case for a TextBox, whose Text property is instead exposed through the UIA Value property.

If the TextBox has an associated TextBlock control which describes the purpose of the TextBox, consider having the TextBox's UIA Name property set from the TextBlock's text. This approach avoids the need to add a localized string specifically for the accessible name of the TextBox. To have the UIA Name set in this way, set the TextBox's AutomationProperties.LabeledBy property to reference the labelling TextBlock.

If the TextBox has no associated TextBlock control, consider adding a TextBlock in order for your sighted customers to efficiently learn of the purpose of the TextBox, and then reference the TextBlock as described above. If that is not practical, explicitly set an accessible name on the TextBox through its AutomationProperties.Name property.

Note

While setting the accessible properties of a control is typically achieved through markup, in some situations it could be achieved through code-behind. Setting the accessible properties of a control in code-behind

Code Sample 1: Setting the TextBox's accessible name from a nearby TextBlock.

The localization steps for strings exposed through UIA are the same as that used for strings shown visually in the WPF app.

<TextBlock Name="FirstNameLabel" Text="{x:Static local:Resources.firstname}" />
<TextBox AutomationProperties.LabeledBy="{Binding ElementName=FirstNameLabel}" ... />

Code Sample 2: Setting the TextBox's accessible name explicitly because it has no associated TextBlock.

<TextBox AutomationProperties.Name="{x:Static local:Resources.lastname}" ... />