假设button控件应用了如下控件模板:
- <ControlTemplate x:Key="StartActivity" targettype="Button">
- <Grid Width="Auto" Height="62" Margin="0,0">
- <TextBlock Height="0" Margin="0,0" VerticalAlignment="Bottom" Text="" textwrapping="Wrap" x:Name="tbLabel" RenderTransformOrigin="0.5,0.5" HorizontalAlignment="Center" Foreground="#FF0507FA">
- </TextBlock>
- </Grid>
- </ControlTemplate>
那么如果想在代码里访问模板里名为tbLabel的TextBlock控件,该怎么写代码呢?
控件基类Control有个叫GetTemplateChild的方法,但是该方法是Protected型的,所以很显然,我们必须继承基类并且重载OnApplyTemplate来调用该方法,如下:
- public class ActivityControl : Button
- {
- public override void OnApplyTemplate()
- {
- base.OnApplyTemplate();
- //get the textblock control from template
- TextBlock label = GetTemplateChild("tbLabel") as TextBlock;
- }
- }
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。