title: How to Find Children of a UserControl instead of a Window - replacing Window.FindName
body: <p>I currently have a WPF project which has one main Window, and many UserControls which are children of this Window. Many of the children of this window are Tabs. I have successfully replaced my main Window with a User Control that implements almost exactly the same functionality as the Main Window. </p>
  
  <p>Replacing the Window with a UserControl introduced one problem - currently our application determines which programming tab to display based on the parent window by using the <code>Window.FindName</code> method shown below. Therefore I need to replace the <code>Application.Current.MainWindow</code> with an appropriate description of my main user control. See the erroring C# method below and wpf instantiation of the tabs for clarification. </p>
  
  <p><strong>Note Regarding Window.FindName() method</strong> - the reason why it does not work after I replaced it with a UserControl is because the FindName method searches upwards in the visual tree, <a href="https://stackoverflow.com/questions/1764364/why-doesnt-window-findname-discover-the-xname-of-a-button-in-a-child-usercontr/1764596#1764596">as described here</a>. </p>
  
  <p>Does anyone know how to find a user control based on the x:Name, similar to <code>Application.Current.MainWindow</code> ? Also, is there a better way to find the UserControl than looking for the x:Name string in case it gets renamed? </p>
  
  <p>How we currently find the MainWindow - need to now find MainUserControl:</p>
  
  <pre><code>(C#)
  private static void SetCurrentProgram(int num)
      {
          Window window = Application.Current.MainWindow;
          ProgrammingTab programmingTab1 = window.FindName("ProgrammingTab1") as ProgrammingTab;
          ProgrammingTab programmingTab2 = window.FindName("ProgrammingTab2") as ProgrammingTab;
  
          programmingTab1.Visibility = num == 1 ? Visibility.Visible : Visibility.Collapsed;
          programmingTab2.Visibility = num == 2 ? Visibility.Visible : Visibility.Collapsed;
  
      }
  </code></pre>
  
  <p>Instantiation of programming tabs. </p>
  
  <pre><code>(xaml)
  &lt;Grid&gt;
   &lt;ProgrammingControl:ProgrammingTab x:Name="ProgrammingTab1" Program="1" IsVisibleChanged="ProgrammingTab_IsVisibleChanged" /&gt;
   &lt;ProgrammingControl:ProgrammingTab x:Name="ProgrammingTab2" Program="2" IsVisibleChanged="ProgrammingTab_IsVisibleChanged" /&gt;
  &lt;/Grid&gt;
  </code></pre>