WPF-控件-ControlTemplate生成的控件
<Window x:Class="由ControlTemplate生成的控件.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="350" Width="525"> <Window.Resources> <ControlTemplate x:Key="cTemp"> <StackPanel Background="Orange"> <TextBox x:Name="textBox1" Margin="6"/> <TextBox x:Name="textBox2" Margin="6"/> <TextBox x:Name="textBox3" Margin="6"/> </StackPanel> </ControlTemplate> </Window.Resources> <StackPanel Background="Yellow"> <UserControl x:Name="uc" Template="{StaticResource cTemp}" Margin="5"/> <Button Content="Find By Name" Width="120" Height="30" Click="ButtonBase_OnClick"></Button> </StackPanel> </Window>
private void ButtonBase_OnClick(object sender, RoutedEventArgs e) { TextBox tb = this.uc.Template.FindName("textBox1", this.uc) as TextBox; tb.Text = "Hello WPF"; StackPanel sp = tb.Parent as StackPanel; (sp.Children[1] as TextBox).Text = "Hello ControlTemplate"; (sp.Children[2] as TextBox).Text = "I can find you !"; }