0

Is there any possibility to use XPath in order to identify each XAML element in running application?

For example if I have following XAML structure.

<Page>
    <StackPanel>
        <Button />
        <Button />
    </StackPanel>
</Page>

I would like to know XPath of the second button for instance and when I have it, I would like to retrieve the button thanks to XPath afterwards.

I know that I can work with XPath without any problems if I have XmlDocument but I would like to achieve the same stuff with elements from running application if it is possible.

Jakub Krampl
  • 1,774
  • 1
  • 16
  • 24
  • Can you show code that you'd like to write? Not very clear what "the same stuff with elements from running application" means... – Alexei Levenkov Dec 06 '16 at 16:32
  • Sounds like a pretty painful way to go. If you are going to want to access controls from the code-behind it makes sense to name them (x:Name="someName") and then access them based on their name ( Button btn = (Button)this.FindName("someName"); ) – Asnivor Dec 06 '16 at 16:37
  • @AlexeiLevenkov I mean when I click on the second button I would like to get "/Page/StackPanel/Button[index]". Afterwards thanks to XPath expression I would like to find the button. – Jakub Krampl Dec 06 '16 at 16:41
  • @Asnivor Probably painful, however, I am curious whether it is possible or not (without naming). – Jakub Krampl Dec 06 '16 at 16:42
  • 1
    You can... but I don't believe there is an existing implementation. If you really want to make one - read on XPathNavigator which was designed to allow XPath navigation over arbitrary trees... But this approach never took off to my knowledge - so hard to find any useful samples/implementations. – Alexei Levenkov Dec 06 '16 at 17:23
  • @AlexeiLevenkov Thank you for your feedback. If you put this as an answer, I will accept it. – Jakub Krampl Dec 14 '16 at 11:18

1 Answers1

1

There is actually no such XAML structure to apply an XPath on at runtime. The XAML parser will parse your XAML markup and create a tree of elements that make up the user interface that you see on the screen.

So if you need to find the second button in a StackPanel once it has been constructed at runtime you should either look directly in the StackPanel's Children collection:

Button secondButton = sp.Children[1] as Button;

...or use the VisualTreeHelper class to find it in the visual tree: Find control in the visual tree

Community
  • 1
  • 1
mm8
  • 163,881
  • 10
  • 57
  • 88