WinForm桌面应用自动化问题:XPath定位PictureBox按钮点击失败
Let’s break down why your original code isn’t working and fix it step by step:
When you use // in the second XPath query, it searches the entire UI automation tree from the root—ignoring the parent Pane[@AutomationId='Txo'] you already located. This means you might be targeting a wrong picBoxSim element elsewhere in the app, or failing to find the correct child element under your target pane.
Corrected Code
Here’s the fixed version that restricts the search to the parent element’s subtree:
// First locate the parent Txo Pane var txoPane = Driver.Session.FindElementByXPath("//Pane[@AutomationId='Txo']"); // Use .// to search only within the txoPane's context txoPane.FindElementByXPath(".//Pane[@AutomationId='picBoxSim']").Click();
Key Change Explained
The .// prefix tells the XPath search to start from the current element’s context (the txoPane you already found) instead of the root of the UI tree. This ensures you’re clicking exactly the picBoxSim that belongs to your target Txo Pane.
Handling Multiple Similar Items
Since you mentioned there are many such items with unique AutomationIds, here’s how to handle bulk operations:
// Get all Txo Panes in the UI var allTxoPanes = Driver.Session.FindElementsByXPath("//Pane[@AutomationId='Txo']"); foreach (var pane in allTxoPanes) { // Locate and click the Sim button for each pane var simButton = pane.FindElementByXPath(".//Pane[@AutomationId='picBoxSim']"); if (simButton != null && simButton.Enabled) { simButton.Click(); // Add custom logic for each item (like checking Não buttons) here } }
Alternative: Single XPath Query
You can also combine both conditions into one XPath to simplify the code:
Driver.Session.FindElementByXPath("//Pane[@AutomationId='Txo']//Pane[@AutomationId='picBoxSim']").Click();
The double // here means "any descendant of the Txo Pane", which is exactly the scope you need.
内容的提问来源于stack exchange,提问作者Yuri Costa de Oliveira

