FindFirst always returns null AutomationElement

4.6k views Asked by At

I am trying to test some custom controls with the UI Automated framework. One of my controls has a base class of TextBox and the other inherits from Control. I can find my first control with my tests, however no matter what combination I use of TreeScope and property conditions, I cannot find my second custom control within the window.

I declare the custom control in the XAML like so:

<Grid>
    <test:CustomTextBox Height="23" HorizontalAlignment="Left" Margin="12,12,0,0" Name="customTextBox1" VerticalAlignment="Top" Width="120" />
    <test:CustomUserControl Height="25" HorizontalAlignment="Left" Margin="12,62,0,0" Name="customUserControl1" VerticalAlignment="Top" Width="119" />
</Grid>

I have a sample test like the one below.

[Test]
public void TestUsingValuePattern()
{
    // Getting RootElement...
    AutomationElement rootElement = AutomationElement.RootElement;
    Assert.IsNotNull(rootElement);

    // Searching for Test Window...
    AutomationElement windowElement = rootElement.FindFirst(TreeScope.Children, new PropertyCondition(AutomationElement.NameProperty, "TestWindow"));
    Assert.IsNotNull(windowElement);

    // Searching for Custom TextBox control...
    AutomationElement customElement1 = windowElement.FindFirst(TreeScope.Descendants, new PropertyCondition(AutomationElement.AutomationIdProperty, "customTextBox1"));
    Assert.IsNotNull(customElement1);

    // Searching for Custom User control
    AutomationElement customElement2 = windowElement.FindFirst(TreeScope.Descendants, new PropertyCondition(AutomationElement.AutomationIdProperty, "customUserControl1"));
    Assert.IsNotNull(customElement2);
}

Second assertion always returns null so I can't even get started running tests on it. Any suggestions here on what I could possibly do to fix this issue?

2

There are 2 answers

0
BrendanMcK On BEST ANSWER

It looks like you may need to set the AutomationId property in the XAML for it to show up - it doesn't look like the Name property gets exposed as AutomationId.

You might also want use the inspect tool to check that the elements are actually exposed in the automation tree, and have the AutomationId or other properties that you expect.

0
Amit Gajjar On

See check below thread, you need to use AutomationId for each control to get element using it.

http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/b0892b5c-3850-4518-8063-d4eb5a8d9781/