首页 > 解决方案 > 更改 UWP 文本框的屏幕阅读器行为?

问题描述

我编写了一个与 PasswordBox 类似但使用 TextBox 实现的 UserControl。该控件会在键入字符时替换字符为“点”字符,并在我们不想显示实际内容的情况下使用。它可以按预期工作,只是屏幕阅读器会读取输入的每个字符,这有悖于目的。相比之下,当用户在 PasswordBox 中键入字符时,讲述人程序会说“隐藏”而不是键入的键。

当用户在 TextBox 中键入键时,我可以做些什么来改变屏幕阅读器的行为?如果我可以让它说“隐藏”那就太好了,但让屏幕阅读器什么也不说也很好。我查看了 AutomationProperties 类的属性,但没有看到任何明显的东西。

标签: c#xamluwpcontrols

解决方案


在编写 Windows 应用程序时,用于 UI 的类已经提供 UI 自动化支持,它支持辅助功能应用程序和辅助技术,例如屏幕阅读器。PasswordBox 的自动化是PasswordBoxAutomationPeer,您可以在 PasswordBoxAutomationPeer 部分检查 Default peer 实现和覆盖,它覆盖了 IsPassword 方法,可以防止屏幕阅读器读取字符。

因此,您可以从 TextBox 派生一个自定义类,并为您在自定义类中启用的其他功能添加自动化支持。然后覆盖 OnCreateAutomationPeer 以便它返回您的自定义对等点。例如:

public class MyCustomAutomationPeer : FrameworkElementAutomationPeer
{
    public MyCustomAutomationPeer(MyTextBox owner) : base(owner)
    {
    }

    protected override string GetClassNameCore()
    {
        return "MyTextBox";
    }

    protected override bool IsPasswordCore()
    {
        return true;
    }

    protected override AutomationControlType GetAutomationControlTypeCore()
    {
        return AutomationControlType.Edit;
    }
}


public class MyTextBox : TextBox
{
    public MyTextBox()
    {
        // other initialization; DefaultStyleKey etc.
    }

    protected override AutomationPeer OnCreateAutomationPeer()
    {
        return new MyCustomAutomationPeer(this);
    }
}

之后,您可以在 MyTextBox 中用“点”字符替换输入的字符。此外,关于自定义自动化对等体的更多详细信息,您可以参考此文档


推荐阅读