假设button控件应用了如下控件模板:
1.<ControlTemplate x:Key="StartActivity" TargetType="Button">
2. <Grid Width="Auto" Height="62" Margin="0,0,0,0">
3. <TextBlock Height="0" Margin="0,0,0,0" VerticalAlignment="Bottom" Text="" TextWrapping="Wrap" x:Name="tbLabel" RenderTransformOrigin="0.5,0.5" HorizontalAlignment="Center" Foreground="#FF0507FA">
4.
5. </TextBlock>
6. </Grid>
7. </ControlTemplate>
那么如果想在代码里访问模板里名为tbLabel的 TextBlock控件,该怎么写代码呢?
控件基类Control有个叫GetTemplateChild的方法,但是该方法是Protected型的,所以很显然,我们 必须继承基类并且重载OnApplyTemplate来调用该方法,如下:
1.public class ActivityControl : Button
2. {
3. public override void OnApplyTemplate()
4. {
5. base.OnApplyTemplate();
6.
7. //get the textblock control from template
8. TextBlock label = GetTemplateChild("tbLabel") as TextBlock;
9. }
10. }