title: Why can't I access a TextBox by Name with FindName()?
body: <p>Why does <strong>FindName()</strong> return <strong>null</strong> in the following example?</p>
  
  <p><strong>XAML:</strong></p>
  
  <pre><code>&lt;Window x:Class="TestDynamicTextBox343.Window1"
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
      Title="Window1" Height="300" Width="300"&gt;
      &lt;StackPanel&gt;
          &lt;Border &gt;
  
              &lt;DockPanel x:Name="FormBase" LastChildFill="True"&gt;
  
              &lt;/DockPanel&gt;
  
          &lt;/Border&gt;
  
          &lt;Button Content="Save" Click="Button_Click"/&gt;
      &lt;/StackPanel&gt;
  &lt;/Window&gt;
  </code></pre>
  
  <p><strong>Code Behind:</strong></p>
  
  <pre><code>using System;
  using System.Windows;
  using System.Windows.Controls;
  
  namespace TestDynamicTextBox343
  {
      public partial class Window1 : Window
      {
          public Window1()
          {
              InitializeComponent();
  
  
              StackPanel sp = new StackPanel();
              sp.Orientation = Orientation.Horizontal;
  
              TextBlock textBlock = new TextBlock();
              textBlock.Text = "First Name: ";
  
              TextBox textBox = new TextBox();
              textBox.Name = "FirstName";
              textBox.Text = "test";
  
              sp.Children.Add(textBlock);
              sp.Children.Add(textBox);
              FormBase.Children.Add(sp);
  
          }
  
          private void Button_Click(object sender, RoutedEventArgs e)
          {
              TextBox tb = (TextBox)this.FindName("FirstName");
              Console.WriteLine(tb.Text);
          }
      }
  }
  </code></pre>
  
  <h1>Addendum to Answer:</h1>
  
  <p>Thanks a lot, Bruno, that worked well. In order not to add the same name twice, I wrap it with this:</p>
  
  <pre><code>void RegisterTextBox(string textBoxName, TextBox textBox)
  {
      if ((TextBox)this.FindName(textBoxName) != null)
          this.UnregisterName(textBoxName);
      this.RegisterName(textBoxName, textBox);
  }
  </code></pre>
  
  <p>Or if you will be registering anything other than TextBoxes, a generic version:</p>
  
  <pre><code>void RegisterControl&lt;T&gt;(string textBoxName, T textBox)
  {
      if ((T)this.FindName(textBoxName) != null)
          this.UnregisterName(textBoxName);
      this.RegisterName(textBoxName, textBox);
  }
  </code></pre>