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

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

<ControlTemplate x:Key="StartActivity" TargetType="Button">
            <Grid Width="Auto" Height="62" Margin="0,0,0,0">
                <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">

                </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;
        }
    }

posted on 2009-09-18 11:58  云中深海  阅读(223)  评论(0编辑  收藏  举报