0

I am traversing a WPF application through its VisualTree, using the VisualTreeHelper, which is returning DependencyObjects.

for(int i = 0; i < VisualTreeHelper.GetChildrenCount(rootObject); i++) {
    var child = VisualTreeHelper.GetChild(rootObject, i);
}

However, once i find the object i'm looking for (in this case its a button) i need to "press"/invoke it. I've successfully invoked a button using an InvokePattern on an AutomationElement.

private void ClickBtn(AutomationElement btnElement) {
    InvokePattern btnPattern = btnElement.GetCurrentPattern(
        InvokePattern.Pattern) as InvokePattern;
    btnPattern.Invoke();
}

So the problem stands: How do i convert a DependencyObjects into an AutomationElement?
Or: How do i invoke a DependancyObject?
Or: How do i create an AutomationElement that points to the same WPF element as a given DependencyObjects dose?

Edit1:
I've found that i can convert the DependancyObject to a Control.

var childVisual = VisualTreeHelper.GetChild(rootObject, i);
var childInstance = childVisual as Control; 

However the problem stands: How do i invoke a Control?
Or: How do i convert a Control into an AutomationElement?

Olian04
  • 6,480
  • 2
  • 27
  • 54

1 Answers1

0

Turns out i could cast the AutomationElement to a ButtonBase and call its "OnLoad" method through reflection:

var childVisual = VisualTreeHelper.GetChild(rootObject, i);
var btnToInvoke = childVisual as ButtonBase; 
MethodInfo clickMethodInfo = typeof(Button).GetMethod("OnClick",
    BindingFlags.NonPublic | BindingFlags.Instance);
clickMethodInfo.Invoke(btnToInvoke, new object[] {});
Olian04
  • 6,480
  • 2
  • 27
  • 54