如何在Xamarin.Forms中以编程方式访问Narrator与CustomText
Xamarin.Forms 编程调用Narrator读取自定义文本实现方案
基础实现:绑定自定义朗读文本
Xamarin.Forms 内置的 AutomationProperties 附加属性可直接对接各平台屏幕阅读器(Windows平台对应Narrator),无需额外依赖:
- XAML 静态设置示例:
<Entry Text="界面显示内容" AutomationProperties.Name="你需要Narrator朗读的CustomText内容" AutomationProperties.HelpText="可选补充说明文本"/> - C# 动态设置示例:
// 任意控件都可设置自定义朗读文本 var customEntry = new Entry { Text = "界面显示内容" }; AutomationProperties.SetName(customEntry, "需要Narrator朗读的CustomText内容"); // 设置后用户聚焦该控件时,Narrator会自动读取配置的自定义文本
进阶实现:主动触发Narrator朗读(无需用户聚焦控件)
如果需要在业务逻辑中主动唤起Narrator朗读指定内容,需通过依赖服务调用UWP原生API实现:
- 共享项目定义调用接口
public interface IScreenReaderService { void Announce(string customText); } - UWP平台实现接口
[assembly: Dependency(typeof(ScreenReaderService_UWP))] namespace YourAppNamespace.UWP { public class ScreenReaderService_UWP : IScreenReaderService { public void Announce(string customText) { var rootPeer = Windows.UI.Xaml.Automation.Peers.FrameworkElementAutomationPeer.FromElement(Window.Current.Content); if (rootPeer == null) return; rootPeer.RaiseNotificationEvent( Windows.UI.Xaml.Automation.Peers.AutomationNotificationKind.Other, Windows.UI.Xaml.Automation.Peers.AutomationNotificationProcessing.ImportantAll, customText, "CustomTextAnnouncement"); } } } - 共享项目直接调用
DependencyService.Get<IScreenReaderService>().Announce("你要Narrator朗读的CustomText内容");
注意事项
- 需提前在Windows系统设置中开启讲述人功能,否则朗读逻辑不会生效
AutomationProperties.Name的优先级高于控件本身的显示文本,设置后会替代控件默认内容被Narrator读取- 主动通知API仅适配Windows 10 1809及以上版本系统,低版本系统可通过临时创建隐藏控件、设置自定义朗读属性后强制控件聚焦实现朗读效果
内容的提问来源于stack exchange,提问作者Rasika Palanisamy
相关产品推荐
相关产品推荐

