我有一个带有 ListView 控件的 WPF 应用程序来显示错误列表。当我清除项目并将其添加到 ListView 时,Windows 旁白会宣布它们,但 NVDA 阅读器不会。
这是我的代码:
<Window x:Class="ListViewAccessibility.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:ListViewAccessibility"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Grid>
<StackPanel>
<ListView x:Name="errorsListView" Margin="28,0,0,0"
Height="150"
ItemsSource="{Binding Path=ErrorItems}"
AutomationProperties.Name="Errors"
AutomationProperties.LiveSetting="Assertive"
>
<ListView.ItemTemplate>
<DataTemplate >
<WrapPanel >
<TextBlock Text="{Binding ErrorText}" FontWeight="Bold"
AutomationProperties.Name="{Binding ErrorText}" />
</WrapPanel>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
<Button Command="{Binding AddErrorCommand}">Add Item</Button>
</StackPanel>
</Grid>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
DataContext = new MainViewModel();
((INotifyCollectionChanged)errorsListView.Items).CollectionChanged += ListViewCollectionChanged;
}
private void ListViewCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
if (errorsListView.Items?.Count > 0)
{
RaiseListViewLiveRegionChanged();
}
}
private void RaiseListViewLiveRegionChanged()
{
var peer = UIElementAutomationPeer.FromElement(errorsListView);
if (peer == null)
{
peer = UIElementAutomationPeer.CreatePeerForElement(errorsListView);
}
peer.RaiseAutomationEvent(AutomationEvents.LiveRegionChanged);
}
}
public class ErrorInfo
{
public string ErrorText { get; set; }
}
public class MainViewModel : ViewModelBase
{
public ObservableCollection<ErrorInfo> ErrorItems { get; } = new ObservableCollection<ErrorInfo>();
private ICommand _addErrorCommand;
public ICommand AddErrorCommand
{
get
{
return _addErrorCommand ?? (_addErrorCommand = new RelayCommand(() => AddError()));
}
}
int idx = 0;
private void AddError()
{
ErrorItems.Clear();
ErrorItems.Add(new ErrorInfo() { ErrorText = $"New Error {idx++}" });
}
}
Inspect.exe 结果