微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

silverlight之How To:访问控件模板里的控件

假设button控件应用了如下控件模板:

  1. <ControlTemplate x:Key="StartActivity" targettype="Button">
  2.             <Grid Width="Auto" Height="62" Margin="0,0">
  3.                 <TextBlock Height="0" Margin="0,0" VerticalAlignment="Bottom" Text="" textwrapping="Wrap" x:Name="tbLabel" RenderTransformOrigin="0.5,0.5" HorizontalAlignment="Center" Foreground="#FF0507FA">
  4.                 </TextBlock>
  5.             </Grid>
  6.         </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.     }

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐