TextBlock can't be find in DataTemplate when use Coded UI Test

If you use textblock in DataTemplate, such as follow:

 <ListBox x:Name="manageJobsListBox" Grid.Column="1"  
       ItemsSource="{Binding ManageJobsListCollection}"
            Background="Yellow">
      <ListBox.ItemTemplate>
        <DataTemplate>
          <Grid>
            <StackPanel Margin="0,0,4,0" Orientation="Vertical" VerticalAlignment="Bottom">
              <TextBlock HorizontalAlignment="Stretch" Margin="5" Height="15"  Text="dddddddddddd" x:Name="dddewr" Background="Yellow" />
              <Label   Content="{Binding Path=UIJobData.ItemName}"
                            VerticalAlignment="Bottom" HorizontalAlignment="Left" Height="30"
                           Margin="2,0,0,0"  Background="Red"/>
              <local:AutomatableTextBlock HorizontalAlignment="Stretch" Margin="5" Height="15"  Text="{Binding Path=UIJobData.ItemName}" x:Name="hj" Background="Purple" />
            </StackPanel>
          </Grid>
        </DataTemplate>
      </ListBox.ItemTemplate>
    </ListBox>
    

The Textblock can't be find when use Coded UI Test, Label is OK.
We need to custom textblock, as follow, and use as above.

 public class AutomatableTextBlock : TextBlock
    {
        protected override AutomationPeer OnCreateAutomationPeer()
        {
            return new AutomatableTextBlockAutomationPeer(this);
        }

        class AutomatableTextBlockAutomationPeer : TextBlockAutomationPeer
        {
            public AutomatableTextBlockAutomationPeer(TextBlock owner)
                : base(owner)
            { }

            protected override bool IsControlElementCore()
            { return true; }
        }
    }


Details refer:

http://social.msdn.microsoft.com/Forums/en-AU/vsautotest/thread/fcb21b5e-8797-4d1d-92fa-3ad4aa945d51

原文地址:https://www.cnblogs.com/xiaokang088/p/2901592.html