为什么在下面的例子中FindName()返回null?为什么我无法通过名称使用FindName()访问文本框?
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);
}
}
}
补遗答:
非常感谢,布鲁诺,运作良好。为了不添加相同的名称两次,我用这个包起来:
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);
}
我没有得到,如果我应该注册我想用FindName()函数找到的所有名称。我是不是该? – 2012-11-29 10:12:39
@LorenzoSciuto只有你需要的那些,特别是那些将被动画定位的。 – Sabuncu 2014-11-13 20:33:55