ControlTemplate 和 DataTemplate 都是派生自FrameworkTemplate, 这个类有 FindName 方法 访问内部的控件
也就是说只有我们获得了Template 就可以访问内部控件。
对于ControlTemplate,访问控件的Template属性即可。但是对于 DataTemplate 则要麻烦一些
1、访问 ControlTemplate 内部控件
<Window.Resources> <ControlTemplate x:Key="ctemp"> <StackPanel Background="Orange"> <TextBlock x:Name="t1" Margin="6" Background="White"></TextBlock> <TextBlock x:Name="t2" Margin="6,6" Background="White"></TextBlock> <TextBlock x:Name="t3" Margin="6" Background="White"></TextBlock> </StackPanel> </ControlTemplate> </Window.Resources> <StackPanel Background="Yellow"> <UserControl x:Name="uc" Template="{StaticResource ctemp}" Margin="5"></UserControl> <Button Content="Find by Name" Click="Button_Click"></Button> </StackPanel>
private void Button_Click(object sender, RoutedEventArgs e) { TextBlock tb = this.uc.Template.FindName("t1", this.uc) as TextBlock; tb.Text = "Hello Wpf"; StackPanel sp=tb.Parent as StackPanel; var tb2=sp.Children[1] as TextBlock; var tb3=sp.Children[2] as TextBlock; tb2.Text="Control Template"; tb3.Text= "I Can Find you"; }