Search code examples
c#automationui-automationmicrosoft-ui-automation

How can I access the underlying Element of an existing AutomationPeer?


Ive recently started to learn/use the AutomationPeer class and how to override its features. One question that I have, is if there is anyway to Extract the UIElement that was passed passed in during the initializing of the AutomationPeer.

An Example:

public class MyRadMenuItemAutomationPeer : RadMenuItemAutomationPeer
{
    public MyRadMenuItemAutomationPeer(RadMenuItem owner)
      : base(owner)
    {

    }

    protected override List<AutomationPeer> GetChildrenCore()
    {
        //originalPeers at this point is a collection of RadMenuItemAutomationPeer
        var originalPeers = base.GetChildrenCore();
        
        //Id like to take each one of these Peers, and somehow cast them or 
        // create a new collection<MyRadMenuItemAutomationPeer> from the root
        // element in the original peer. I know there is the Owner property but
        // that is protected and not visible from the outside.

        var newPeers = 
             //What should be implemented here? An idea I had is something like:
             // originalPeers.Select(p => new MyRadMenuItemAutomationPeer(p.Element))
            //     .ToList(); where p.Element is the way to get the element

        //return newPeers Collection
        return newPeers;
    }

    protected override string GetNameCore()
    {
        //Logic to determing the name Property
        return nameValue;
    }
}

Solution

  • The solution presented by Simon Mourier above worked great. He left it as a sub comment, so I could not mark it as an answer.

    Many classes derived from AutomationPeer have an Owner property that correspond to the related "object" in general. For UIElementAutomationPeer, the Owner is the related UIElement. So you could try to cast any AutomationPeer into a given derived class, and check that. Is that what you're looking for?