爲什麼在下面的例子中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