Wpf 用户控件使UI元素不受UIAutomation的影响

Wpf 用户控件使UI元素不受UIAutomation的影响,wpf,ui-automation,Wpf,Ui Automation,我有一个自动化客户端,它使用AutomationElement.FromPoint方法获取光标下的AutomationElement: AutomationElement element = AutomationElement.FromPoint(point); 通常这很有效,但我在某些WPF应用程序中不断遇到问题。当用户控件与另一个重要的UI元素位于同一UI级别时,就会出现问题 例如: <Window x:Class="wpfTestApp.MainWindow" xmlns

我有一个自动化客户端,它使用AutomationElement.FromPoint方法获取光标下的AutomationElement:

 AutomationElement element = AutomationElement.FromPoint(point);
通常这很有效,但我在某些WPF应用程序中不断遇到问题。当用户控件与另一个重要的UI元素位于同一UI级别时,就会出现问题

例如:

<Window x:Class="wpfTestApp.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525" xmlns:c="clr-namespace:wpfTestApp">
<Window.Resources>
    <c:NameList x:Key="NameListData"/>
</Window.Resources>
    <Grid>
        <ListBox ItemsSource="{Binding Source={StaticResource NameListData}}" 
             Height="300" HorizontalAlignment="Left" Margin="10,10,0,0" Name="listBox1" 
             VerticalAlignment="Top" Width="153" >
        </ListBox>
        <UserControl Name="exampleUserControl">
              <TextBlock Visibility="Hidden">Loading...</TextBlock>
        </UserControl>
    </Grid>
</Window>

加载。。。
当我试图指向任何listbox项(甚至listbox本身)时,我得到的只是“exampleUserControl”

我知道还有其他方法可以获取不依赖于位置的AutomationElements,但在本例中,这是我唯一的选择,因为我们试图获取光标下的元素。问题是,在这种情况下,重要元素(即listbox项)被这个不重要的项(“exampleUserControl”包含“Loading…”文本)所覆盖


除了FromPoint方法,还有什么替代方法,或者我可以让它忽略这些元素吗?

有几种方法可以找到/搜索元素

您可以在MSDN上找到这些接口 例如:

AutomationElement.FindFirst-

AutomationElement.FindAll-

//示例:查找第一个元素和classname=”“SciCalc” AutomationElement calcRoot=AutomationElement.RootElement.FindFirst(TreeScope.Children, 新属性条件(AutomationElement.ClassNameProperty,“SciCalc”)

“AutomationElement.RootElement”是当前打开的所有窗口和控件的父级。 为了提高性能,您可以先找到目标窗口,然后扫描目标窗口AutomationElement上的控件


例如:您可以先通过“AutomationElement.FindFirst”或“AutomationElement.FromHandle”找到并创建目标WPF窗口,然后在目标窗口上搜索您的列表框。

问题的干净解决方案是将
可见性=“Hidden”
设置为
用户控件,而不是
文本块