Share via


WinForms: Setting a value on a button

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

Buttons in my app expose current values visually. (For example, a button for selecting a text color conveys the currently selected color.) My customers needs the buttons to expose those values programmatically for screen readers to announce.

Suggested Fix

Consider overriding the button's AccessibleObject in order to expose the custom Value property on the button. This Value gets exposed through the UI Automation (UIA) API as the Value property of the Value control pattern.

Code Sample: Provide a custom Value through an overridden AccessibleObject

public class ButtonWithValue : Button
{
    protected override AccessibleObject CreateAccessibilityInstance()
    {
        return new ButtonWithValueAccessibleObject(this);
    }

    protected class ButtonWithValueAccessibleObject : ControlAccessibleObject
    {
        public ButtonWithValueAccessibleObject(ButtonWithValue owner) : base(owner)
        {
        }

		// Initialize the value to some default state.
        private string _value = Resources.ResourceManager.GetString("BlueColor");

        public override string Value
        {
            get
            {
                return _value;
            }
            set
            {
                _value = Value;
            }
        }
    }
}