在下面的示例中,为什么
FindName()
返回null
?
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>
后台代码:
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);
}
}
}
答案补充:
非常感谢,Bruno,这很有效。为了不重复添加相同的名称,我用以下方式进行包装:
void RegisterTextBox(string textBoxName, TextBox textBox)
{
if ((TextBox)this.FindName(textBoxName) != null)
this.UnregisterName(textBoxName);
this.RegisterName(textBoxName, textBox);
}
如果您要注册除文本框以外的任何内容,可以使用通用版本:
void RegisterControl<T>(string textBoxName, T textBox)
{
if ((T)this.FindName(textBoxName) != null)
this.UnregisterName(textBoxName);
this.RegisterName(textBoxName, textBox);
}