I'm trying to use TestStack.White to simulate a click on a menu subitem in a WPF application. That subitem is added at runtime, and I have little control over how it's created. I don't seem to be able to find the menu subitem to click.
I have tried this:
MainWindow.xaml
<Window x:Class="WpfApplication3.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525" Loaded="Window_Loaded">
<DockPanel>
<Menu DockPanel.Dock="Top">
<MenuItem x:Name="MainMenu" Header="Menu">
<MenuItem x:Name="SubMenu" Header="Sub Menu"/>
</MenuItem>
</Menu>
</DockPanel>
</Window>
MainWindow.cs
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
for (int i = 0; i < 5; i++)
{
var newItem = new MenuItem();
newItem.Header = string.Format("Item {0}", i + 1);
newItem.Name = string.Format("Item{0}", i + 1);
this.SubMenu.Items.Add(newItem);
newItem.Click += new RoutedEventHandler(MenuItemClickHandler);
}
}
private void MenuItemClickHandler(object sender, RoutedEventArgs e)
{
var menuItem = (MenuItem)sender;
MessageBox.Show(this, "You clicked " + menuItem.Header, "Menu Click", MessageBoxButton.OK, MessageBoxImage.Information);
}
}
ConsoleApplication1.Program
class Program
{
static void Main(string[] args)
{
string path = @"C:\{path}\WpfApplication3\bin\Debug";
string prog = Path.Combine(path, "WpfApplication3.exe");
TestStack.White.Application app = TestStack.White.Application.Launch(prog);
var window = app.GetWindow(SearchCriteria.ByText("MainWindow"), InitializeOption.WithCache);
window.WaitWhileBusy();
var menu = window.MenuBar.MenuItem("Menu", "SubMenu", "Item2");
menu.Click();
}
}
I'm unsure how to find the menu subitems, and I'm guessing its because they weren't there when the application was compiled ?
Apologies for the Noddy example, but WPF isn't my forte, and neither is TestStack.White
Here's where I got to (which works), but why are the added menu items "ChildMenus", and not findable in the same way the "menu" and "sub menu" are found ? Also, why is the child menu found by a name of "item 2" (and not, as I thought would be the case, of "item2") ? Why the apparent mix up of "name" and "header" used in the xaml ?