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 Behind:
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 Answer:
Thanks a lot, Bruno, that worked well. In order not to add the same name twice, I wrap it with this:
void RegisterTextBox(string textBoxName, TextBox textBox)
{
if ((TextBox)this.FindName(textBoxName) != null)
this.UnregisterName(textBoxName);
this.RegisterName(textBoxName, textBox);
}
Or if you will be registering anything other than TextBoxes, a generic version:
void RegisterControl<T>(string textBoxName, T textBox)
{
if ((T)this.FindName(textBoxName) != null)
this.UnregisterName(textBoxName);
this.RegisterName(textBoxName, textBox);
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…