Why does FindName () return null in the following example?
XAML:
<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"> <StackPanel> <Border > <DockPanel x:Name="FormBase" LastChildFill="True"> </DockPanel> </Border> <Button Content="Save" Click="Button_Click"/> </StackPanel> </Window>
Code for:
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); } } }
Addendum to the answer:
Thanks a lot, Bruno, it worked out well. In order not to add the same name twice, I conclude it with the following:
void RegisterTextBox(string textBoxName, TextBox textBox) { if ((TextBox)this.FindName(textBoxName) != null) this.UnregisterName(textBoxName); this.RegisterName(textBoxName, textBox); }
Or if you register anything other than TextBoxes, the generic version:
void RegisterControl<T>(string textBoxName, T textBox) { if ((T)this.FindName(textBoxName) != null) this.UnregisterName(textBoxName); this.RegisterName(textBoxName, textBox); }
c # wpf xaml textbox
Edward tanguay
source share