开发者

How to override the ControlTemplate of a UserControl

How can I know the default template element of a usercontrol when I trying to override it? For example somebody have overrided the TabControl's template like this.

<TabControl>
    <TabControl.Template>
        <ControlTemplate TargetType="TabControl">
            <StackPanel>
                <ScrollViewer HorizontalScrollBarVisibility="Visible" VerticalScrollBarVisibility="Disabled">
                    <TabPanel x:Name="HeaderPanel"
                          Panel.ZIndex ="1" 
                          KeyboardNavigation.TabIndex="1"
                          Grid.Column="0"
                          Grid.Row="0"
                          Margin="2,2,2,0"
                          IsItemsHost="true"/>
                </ScrollViewer>
                <ContentPresenter x:Name="PART_SelectedContentHost"
                                      SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"
                                   开发者_开发百科   Margin="{TemplateBinding Padding}"
                                      ContentSource="SelectedContent"/>
            </StackPanel>
        </ControlTemplate>
    </TabControl.Template>
    <TabItem Header="TabItem1">TabItem1 Content</TabItem>
    <TabItem Header="TabItem2">TabItem2 Content</TabItem>
</TabControl>

How does he know there is <StackPanel> and <ContentPresenter> in the TabControl's template?


The TabControl class has a [TemplatePart] attribute that indicates mandatory parts of the template:

[StyleTypedPropertyAttribute(Property = "ItemContainerStyle", StyleTargetType = typeof(TabItem))]
[TemplatePartAttribute(Name = "PART_SelectedContentHost", Type = typeof(ContentPresenter))]
public class TabControl : Selector

In this case the template must contain a ContentPresenter named PART_SelectedContentHost. Everything else is optional, you can put anything you like in the template (as long as it makes sense of course).


When you are overriding a ControlTemplate for any control, you are defining how it will look. The <StackPanel> is just the layout control you are using, it could be a grid or any other layout control.

However the is something it needs to be there. If you look at the WPF control hierarchy, you can see several types of controls at the base levels, after Control, FrameworkElement, etc:

  • <ContentControl>
  • <HeaderedContentControl>
  • <ItemsControl>
  • <HeaderedItemsControl>

Each one of these have specific rendering options and parts. In your case a <TabControl> is an <Selector> which is a special type of an <ItemsControl>. This Selector has a Content and a TabPanel, thus the <TabPanel> and the <ContentPresenter> (which tells WPF where to render the Content).

The best way to aquire this knowledge is by looking at the default WPF templates for each control, for example the TabControl default template for WPF4 is here


See MSDN for default templates and styles.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜