获取 WPF UserControl 的 AutomationElement

Get AutomationElement for a WPF UserControl

我想在测试期间使用 Windows AutomationElements 来模拟用户输入。 我的特殊用例是操纵 ListBox 选择,根据我在网上找到的内容,我的列表框需要一个 AutomationElement 才能操纵它。

假设我有一个像这样的window:

<Window x:Class="CryptoAdmin_Test.Helper.FreshWindow"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             xmlns:local="clr-namespace:CryptoAdmin_Test.Helper">
    <StackPanel>
        <UserControl x:FieldModifier="public" x:Name="FindMe" />
    </StackPanel>
</Window>

因为我有对 UserControl 的引用,所以我应该能够在不从桌面开始搜索的情况下找到它 (AutomationElement.RootElement)。

为我的 window.FindMe UserControl 获得 AutomationElement 最快的方法是什么?

使用 AutomationElement.RootElement.FindFirst(...); 将从桌面开始,我没有看到一种通用的方法可以使此搜索快速而不会出现误报的可能性。

这应该是找到它的最快方法。这还假设您给 window 一个名称,否则很难找到它,除非您从您的应用程序启动该进程并为其提供进程 ID。

AutomationElement mainWindow = AutomationElement.RootElement.FindFirst(TreeScope.Children, new PropertyCondition(AutomationElement.NameProperty, "MainWindow"));
AutomationElement findMe = mainWindow.FindFirst(TreeScope.Children, new PropertyCondition(AutomationElement.NameProperty, "FindMe"));

由于 TreeScope 设置为子项,因此在查找相关元素时不会扫描整棵树。根据您的用户控件执行的操作,您返回的元素可能有些无用。如果不为您的控件实现一些自定义模式,您唯一能做的就是从中获取其他元素。