silverlight如何訪問控制項範本裡的控制項

來源:互聯網
上載者:User

假設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. }

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.