如何引用控件模板中的元素

时间:2009-08-18 16:18:41

标签: wpf controltemplate

说我想在CheckBox内加Button。反正我是否在代码中引用了该复选框?即在Window1.cs中,我想写一些类似于:testButton.innerCheckBox.DoStuff();

的内容
    <ControlTemplate TargetType="{x:Type Button}">                          
        <Microsoft_Windows_Themes:ButtonChrome SnapsToDevicePixels="true" x:Name="Chrome" BorderBrush="{TemplateBinding BorderBrush}" Fill="{TemplateBinding Background}" RenderDefaulted="{TemplateBinding IsDefaulted}" RenderMouseOver="{TemplateBinding IsMouseOver}" RenderPressed="{TemplateBinding IsPressed}" ThemeColor="NormalColor">
        <Grid Width="32.083" Height="13.277">
            <ContentPresenter SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" HorizontalAlignment="Stretch" Margin="{TemplateBinding Padding}" VerticalAlignment="Stretch" RecognizesAccessKey="True" d:LayoutOverrides="Width, Height"/>
            <CheckBox x:Name="innerCheckBox" HorizontalAlignment="Left" VerticalAlignment="Top" Content="CheckBox"/>
        </Grid>
        </Microsoft_Windows_Themes:ButtonChrome>
    </ControlTemplate>

1 个答案:

答案 0 :(得分:4)

CheckBox innerCheckBox = testButton.Template.FindName("innerCheckBox", testButton) as CheckBox;