title: How to use TestStack.White to simulate click on a dynamic MenuItem in WPF?
body: <p>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.</p>
  
  <p>I have tried this:</p>
  
  <p><strong>MainWindow.xaml</strong></p>
  
  <pre><code>&lt;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"&gt;
      &lt;DockPanel&gt;
          &lt;Menu DockPanel.Dock="Top"&gt;
              &lt;MenuItem x:Name="MainMenu" Header="Menu"&gt;
                  &lt;MenuItem x:Name="SubMenu" Header="Sub Menu"/&gt;
              &lt;/MenuItem&gt;
          &lt;/Menu&gt;
      &lt;/DockPanel&gt;
  &lt;/Window&gt;
  </code></pre>
  
  <p><strong>MainWindow.cs</strong></p>
  
  <pre><code>public partial class MainWindow : Window
  {
      public MainWindow()
      {
          InitializeComponent();
      }
  
      private void Window_Loaded(object sender, RoutedEventArgs e)
      {
          for (int i = 0; i &lt; 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);
      }
  }
  </code></pre>
  
  <p><strong>ConsoleApplication1.Program</strong></p>
  
  <pre><code>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();
      }
  }
  </code></pre>
  
  <p>I'm unsure how to find the menu subitems, and I'm guessing its because they weren't there when the application was compiled ?</p>
  
  <p><em>Apologies for the Noddy example, but WPF isn't my forte, and neither is TestStack.White</em></p>