首页 > 解决方案 > 如何隐藏 WPF 元素以与自动化框架一起正常工作?

问题描述

隐藏 WPF 控件的最常见方法是将Visibility属性设置为HiddenCollapsed。当我为示例应用程序执行此操作时,我试图通过自动化框架找到这些元素,我得到了IsOffscreen标志设置为true.

例如:

<Label Content="Hidden label" Visibility="Hidden"/>

可见性:隐藏

<Label Content="Collapsed label" Visibility="Collapsed"/>

可见性:已折叠

从我的角度来看,它看起来很合理,但自动化框架文档: https ://docs.microsoft.com/en-us/windows/desktop/winauto/uiauto-automation-element-propids 说:

最终用户根本无法感知或“以编程方式隐藏”的对象(例如,已关闭的对话框,但底层对象仍由应用程序缓存)不应出现在自动化元素树中首先(而不是将 IsOffscreen 的状态设置为 TRUE)。

我怎样才能达到文档中指出的结果?

标签: c#wpfautomated-testsui-automation

解决方案


面对类似的问题,将 Visibilty 设置为 hidden/Collapsed 不会从可视树中删除元素,即使控件在视觉上不可见。目前据我所知,没有其他属性可以从可视树中删除该元素。

作为一种解决方法,您可以使用带有触发器的ContentPresenter在运行时包含或排除控件。

例如,在下面的代码片段中,我正在根据条件决定要包含哪个标签。它是在运行时决定的,并且只有一个包含在可视化树中。

<ContentPresenter Content="{Binding}">
<ContentPresenter.Resources>
    <DataTemplate x:Key="LabelContent1">
        <Label Content="Dummy" />
    </DataTemplate>
    <DataTemplate x:Key="LabelContent2">
        <Label Content="Dummy" />
    </DataTemplate>
</ContentPresenter.Resources>
<ContentPresenter.Style>
    <Style TargetType="{x:Type ContentPresenter}">
        <Setter Property="ContentTemplate" Value="{StaticResource LabelContent1}" />
        <Style.Triggers>
            <DataTrigger Binding="{Binding Converter={Binding Path=LabelText}}" Value="{x:Null}">
                <Setter Property="ContentTemplate" Value="{StaticResource LabelContent2}" />
            </DataTrigger>
        </Style.Triggers>
    </Style>
</ContentPresenter.Style>

参考: https ://tyrrrz.me/blog/conditional-content-presenting-via-wpf-contentpresenter


推荐阅读