WPF ToggleButton 的 AutomationElement - 具有 ClassName 按钮

AutomationElement for WPF ToggleButton - have ClassName Button

我在工具栏中使用 ToggleButtons,我想在 UI 自动化测试中获取和使用它们,但是当我检查 AutomationElement.Current 这些按钮时,它的类名 属性是 Button,而我希望 ToggleButton

xaml不是很直观,所以我在这里提一下:

<ToolBar ItemsSource="{Binding}"/>

对于 ItemsSource 中的类型,我有一个 DataTemplate:

<DataTemplate DataType="{x:Type myViewModelType}">
    <ContentPresenter Content="{Binding}" ContentTemplate="{StaticResource MyToolBarElementTemplate}">
        <ContentPresenter.Resources>
            <Style TargetType="{x:Type ToggleButton}" BasedOn="{StaticResource ThisStyleSetsWidthAndHeight}"/>
         </ContentPresenter.Resources>
    </ContentPresenter>
</DataTemplate>

样式定义如下:

<Style TargetType="{x:Type ButtonBase}" x:Key="ThisStyleSetsWidthAndHeight"> 
    <Setter Property="styles:AttachedProperties.ContentWidth" Value="32"/>
    <Setter Property="styles:AttachedProperties.ContentHeight" Value="32"/>
</Style>

内容模板如下所示:

<DataTemplate x:Key="MyToolBarElementTemplate" DataType="{x:Type myViewModelType}">
    <ToggleButton x:Name="AutomationIdThatIGetOk">
        ... 
    </ToggleButton>
</DataTemplate>

我对 Automation Framework 有点陌生,我想它与所有这些模板和样式有关,但是有什么方法可以为这个 ToggleButton 创建正确的 AutomationPeer 实例吗?

...but when I check AutomationElement.Current for these buttons, its ClassName property is Button, while I would expect ToggleButton

您的期望是错误的,因为 ToggleButtonAutomationPeer class 实际上 returns 来自其 GetClassNameCore() 方法的 string "Button":https://referencesource.microsoft.com/#PresentationFramework/src/Framework/System/Windows/Automation/Peers/ToggleButtonAutomationPeer.cs,a58abe77888c16cd

所以你得到了正确的实例。