ControlTemplate ControlTemplate ControlTemplate ControlTemplate Class

Definition

Specifies the visual structure and behavioral aspects of a Control that can be shared across multiple instances of the control.

public ref class ControlTemplate : System::Windows::FrameworkTemplate
[System.Windows.Localizability(System.Windows.LocalizationCategory.None, Readability=System.Windows.Readability.Unreadable)]
[System.Windows.Markup.DictionaryKeyProperty("TargetType")]
public class ControlTemplate : System.Windows.FrameworkTemplate
type ControlTemplate = class
    inherit FrameworkTemplate
Public Class ControlTemplate
Inherits FrameworkTemplate
Inheritance
Attributes

Examples

The following shows a Button Style that sets the ControlTemplate of a Button:

<Style TargetType="Button">
  <!--Set to true to not get any properties from the themes.-->
  <Setter Property="OverridesDefaultStyle" Value="True"/>
  <Setter Property="Template">
    <Setter.Value>
      <ControlTemplate TargetType="Button">
        <Grid>
          <Ellipse Fill="{TemplateBinding Background}"/>
          <ContentPresenter HorizontalAlignment="Center"
                            VerticalAlignment="Center"/>
        </Grid>
      </ControlTemplate>
    </Setter.Value>
  </Setter>
</Style>

When this gets applied, the Button appears as an Ellipse:

Button ControlTemplate sample

When you set the Template property of a Control to a new ControlTemplate as in the above example, you are replacing the entire template. What the Button looks like when it is in focus or pressed is all part of the default appearance of the button that you are replacing. Therefore, depending on your needs, you may want to put in your definition what your button should look like when it is pressed, and so on, as in the following example:

<Style TargetType="Button">
  <Setter Property="SnapsToDevicePixels"
          Value="true" />
  <Setter Property="OverridesDefaultStyle"
          Value="true" />
  <Setter Property="FocusVisualStyle"
          Value="{StaticResource ButtonFocusVisual}" />
  <Setter Property="MinHeight"
          Value="23" />
  <Setter Property="MinWidth"
          Value="75" />
  <Setter Property="Template">
    <Setter.Value>
      <ControlTemplate TargetType="Button">
        <Border TextBlock.Foreground="{TemplateBinding Foreground}"
                x:Name="Border"
                CornerRadius="2"
                BorderThickness="1">
          <Border.BorderBrush>
            <LinearGradientBrush StartPoint="0,0"
                                 EndPoint="0,1">
              <LinearGradientBrush.GradientStops>
                <GradientStopCollection>
                  <GradientStop Color="{DynamicResource BorderLightColor}"
                                Offset="0.0" />
                  <GradientStop Color="{DynamicResource BorderDarkColor}"
                                Offset="1.0" />
                </GradientStopCollection>
              </LinearGradientBrush.GradientStops>
            </LinearGradientBrush>

          </Border.BorderBrush>
          <Border.Background>
            <LinearGradientBrush EndPoint="0.5,1"
                                 StartPoint="0.5,0">
              <GradientStop Color="{DynamicResource ControlLightColor}"
                            Offset="0" />
              <GradientStop Color="{DynamicResource ControlMediumColor}"
                            Offset="1" />
            </LinearGradientBrush>
          </Border.Background>
          <VisualStateManager.VisualStateGroups>
            <VisualStateGroup x:Name="CommonStates">
              <VisualStateGroup.Transitions>
                <VisualTransition GeneratedDuration="0:0:0.5" />
                <VisualTransition GeneratedDuration="0"
                                  To="Pressed" />
              </VisualStateGroup.Transitions>
              <VisualState x:Name="Normal" />
              <VisualState x:Name="MouseOver">
                <Storyboard>
                  <ColorAnimationUsingKeyFrames Storyboard.TargetProperty="(Panel.Background).
                      (GradientBrush.GradientStops)[1].(GradientStop.Color)"
                                                Storyboard.TargetName="Border">
                    <EasingColorKeyFrame KeyTime="0"
                                         Value="{StaticResource ControlMouseOverColor}" />
                  </ColorAnimationUsingKeyFrames>
                </Storyboard>
              </VisualState>
              <VisualState x:Name="Pressed">
                <Storyboard>
                  <ColorAnimationUsingKeyFrames Storyboard.TargetProperty="(Panel.Background).
                      (GradientBrush.GradientStops)[1].(GradientStop.Color)"
                                                Storyboard.TargetName="Border">
                    <EasingColorKeyFrame KeyTime="0"
                                         Value="{StaticResource ControlPressedColor}" />
                  </ColorAnimationUsingKeyFrames>
                  <ColorAnimationUsingKeyFrames Storyboard.TargetProperty="(Border.BorderBrush).
                      (GradientBrush.GradientStops)[0].(GradientStop.Color)"
                                                Storyboard.TargetName="Border">
                    <EasingColorKeyFrame KeyTime="0"
                                         Value="{StaticResource PressedBorderDarkColor}" />
                  </ColorAnimationUsingKeyFrames>
                  <ColorAnimationUsingKeyFrames Storyboard.TargetProperty="(Border.BorderBrush).
                      (GradientBrush.GradientStops)[1].(GradientStop.Color)"
                                                Storyboard.TargetName="Border">
                    <EasingColorKeyFrame KeyTime="0"
                                         Value="{StaticResource PressedBorderLightColor}" />
                  </ColorAnimationUsingKeyFrames>
                </Storyboard>
              </VisualState>
              <VisualState x:Name="Disabled">
                <Storyboard>
                  <ColorAnimationUsingKeyFrames Storyboard.TargetProperty="(Panel.Background).
                      (GradientBrush.GradientStops)[1].(GradientStop.Color)"
                                                Storyboard.TargetName="Border">
                    <EasingColorKeyFrame KeyTime="0"
                                         Value="{StaticResource DisabledControlDarkColor}" />
                  </ColorAnimationUsingKeyFrames>
                  <ColorAnimationUsingKeyFrames
                      Storyboard.TargetProperty="(TextBlock.Foreground).(SolidColorBrush.Color)"
                                                Storyboard.TargetName="Border">
                    <EasingColorKeyFrame KeyTime="0"
                                         Value="{StaticResource DisabledForegroundColor}" />
                  </ColorAnimationUsingKeyFrames>
                  <ColorAnimationUsingKeyFrames Storyboard.TargetProperty="(Border.BorderBrush).
                      (GradientBrush.GradientStops)[1].(GradientStop.Color)"
                                                Storyboard.TargetName="Border">
                    <EasingColorKeyFrame KeyTime="0"
                                         Value="{StaticResource DisabledBorderDarkColor}" />
                  </ColorAnimationUsingKeyFrames>
                </Storyboard>
              </VisualState>
            </VisualStateGroup>
          </VisualStateManager.VisualStateGroups>
          <ContentPresenter Margin="2"
                            HorizontalAlignment="Center"
                            VerticalAlignment="Center"
                            RecognizesAccessKey="True" />
        </Border>
        <ControlTemplate.Triggers>
          <Trigger Property="IsDefault"
                   Value="true">

            <Setter TargetName="Border"
                    Property="BorderBrush">
              <Setter.Value>
                <LinearGradientBrush StartPoint="0,0"
                                     EndPoint="0,1">
                  <GradientBrush.GradientStops>
                    <GradientStopCollection>
                      <GradientStop Color="{DynamicResource DefaultBorderBrushLightBrush}"
                                    Offset="0.0" />
                      <GradientStop Color="{DynamicResource DefaultBorderBrushDarkColor}"
                                    Offset="1.0" />
                    </GradientStopCollection>
                  </GradientBrush.GradientStops>
                </LinearGradientBrush>

              </Setter.Value>
            </Setter>
          </Trigger>
        </ControlTemplate.Triggers>
      </ControlTemplate>
    </Setter.Value>
  </Setter>
</Style>

Note that this example references resources that are not shown here. For the complete sample, see Styling with ControlTemplates Sample. That sample provides examples of control templates for many controls and is the best way for you to get started with creating control templates.

Remarks

The ControlTemplate allows you to specify the visual structure of a control. The control author can define the default ControlTemplate and the application author can override the ControlTemplate to reconstruct the visual structure of the control.

Control templating is one of the many features offered by the WPF styling and templating model. The styling and templating model provides you with such great flexibility that in many cases you do not need to write your own controls. If you are an application author that wants to change the visualization of your control or to replace the ControlTemplate of an existing control, see the Styling and Templating topic for examples and an in-depth discussion.

If you are writing your own control, see "Create a Custom Control" in the Control Authoring Overview.

A ControlTemplate is intended to be a self-contained unit of implementation detail that is invisible to outside users and objects, including styles. The only way to manipulate the content of the control template is from within the same control template.

XAML Property Element Usage

<ControlTemplate>  
  <VisualTreeRootNode > VisualTreeNodeContents  
  </VisualTreeRootNode >  
</ControlTemplate>  

XAML Values

ControlTemplate
Object element for ControlTemplate or a derived class.

VisualTreeRootNode
A single XAML element as the immediate child of the ControlTemplate (or a derived class). Templates must have a single root node. In order to generate a useful template, the element chosen as VisualTreeRootNode is expected to support a content model of its own, often a model that supports multiple child elements.

VisualTreeNodeContents
One or more elements that complete the intended template. If the element chosen as VisualTreeRootNode only supports a single child, then there can only be one element declared as VisualTreeNodeContents. It is also possible (though uncommon) to provide text content if the chosen VisualTreeRootNode supports a text content property.

Constructors

ControlTemplate() ControlTemplate() ControlTemplate() ControlTemplate()

Initializes a new instance of the ControlTemplate class.

ControlTemplate(Type) ControlTemplate(Type) ControlTemplate(Type) ControlTemplate(Type)

Initializes a new instance of the ControlTemplate class with the specified target type.

Properties

Dispatcher Dispatcher Dispatcher Dispatcher

Gets the Dispatcher this DispatcherObject is associated with.

(Inherited from DispatcherObject)
HasContent HasContent HasContent HasContent

Gets a value that indicates whether this template has optimized content.

(Inherited from FrameworkTemplate)
ISealable.CanSeal ISealable.CanSeal ISealable.CanSeal ISealable.CanSeal Inherited from FrameworkTemplate
ISealable.IsSealed ISealable.IsSealed ISealable.IsSealed ISealable.IsSealed Inherited from FrameworkTemplate
IsSealed IsSealed IsSealed IsSealed

Gets a value that indicates whether this object is in an immutable state so it cannot be changed.

(Inherited from FrameworkTemplate)
Resources Resources Resources Resources

Gets or sets the collection of resources that can be used within the scope of this template.

(Inherited from FrameworkTemplate)
TargetType TargetType TargetType TargetType

Gets or sets the type for which this ControlTemplate is intended.

Template Template Template Template

Gets or sets a reference to the object that records or plays the XAML nodes for the template when the template is defined or applied by a writer.

(Inherited from FrameworkTemplate)
Triggers Triggers Triggers Triggers

Gets a collection of TriggerBase objects that apply property changes or perform actions based on specified conditions.

VisualTree VisualTree VisualTree VisualTree

Gets or sets the root node of the template.

(Inherited from FrameworkTemplate)

Methods

CheckAccess() CheckAccess() CheckAccess() CheckAccess()

Determines whether the calling thread has access to this DispatcherObject.

(Inherited from DispatcherObject)
Equals(Object) Equals(Object) Equals(Object) Equals(Object)

Determines whether the specified object is equal to the current object.

(Inherited from Object)
FindName(String, FrameworkElement) FindName(String, FrameworkElement) FindName(String, FrameworkElement) FindName(String, FrameworkElement)

Finds the element associated with the specified name defined within this template.

(Inherited from FrameworkTemplate)
GetHashCode() GetHashCode() GetHashCode() GetHashCode()

Serves as the default hash function.

(Inherited from Object)
GetType() GetType() GetType() GetType()

Gets the Type of the current instance.

(Inherited from Object)
LoadContent() LoadContent() LoadContent() LoadContent()

Loads the content of the template as an instance of an object and returns the root element of the content.

(Inherited from FrameworkTemplate)
MemberwiseClone() MemberwiseClone() MemberwiseClone() MemberwiseClone()

Creates a shallow copy of the current Object.

(Inherited from Object)
RegisterName(String, Object) RegisterName(String, Object) RegisterName(String, Object) RegisterName(String, Object)

Registers a new name/object pair into the current name scope.

(Inherited from FrameworkTemplate)
Seal() Seal() Seal() Seal()

Locks the template so it cannot be changed.

(Inherited from FrameworkTemplate)
ShouldSerializeResources(XamlDesignerSerializationManager) ShouldSerializeResources(XamlDesignerSerializationManager) ShouldSerializeResources(XamlDesignerSerializationManager) ShouldSerializeResources(XamlDesignerSerializationManager)

Returns a value that indicates whether serialization processes should serialize the value of the Resources property on instances of this class.

(Inherited from FrameworkTemplate)
ShouldSerializeVisualTree() ShouldSerializeVisualTree() ShouldSerializeVisualTree() ShouldSerializeVisualTree()

Returns a value that indicates whether serialization processes should serialize the value of the VisualTree property on instances of this class.

(Inherited from FrameworkTemplate)
ToString() ToString() ToString() ToString()

Returns a string that represents the current object.

(Inherited from Object)
UnregisterName(String) UnregisterName(String) UnregisterName(String) UnregisterName(String)

Removes a name/object mapping from the XAML namescope.

(Inherited from FrameworkTemplate)
ValidateTemplatedParent(FrameworkElement) ValidateTemplatedParent(FrameworkElement) ValidateTemplatedParent(FrameworkElement) ValidateTemplatedParent(FrameworkElement)

Checks the templated parent against a set of rules.

VerifyAccess() VerifyAccess() VerifyAccess() VerifyAccess()

Enforces that the calling thread has access to this DispatcherObject.

(Inherited from DispatcherObject)

Explicit Interface Implementations

INameScope.FindName(String) INameScope.FindName(String) INameScope.FindName(String) INameScope.FindName(String)

Returns an object that has the provided identifying name.

(Inherited from FrameworkTemplate)
IQueryAmbient.IsAmbientPropertyAvailable(String) IQueryAmbient.IsAmbientPropertyAvailable(String) IQueryAmbient.IsAmbientPropertyAvailable(String) IQueryAmbient.IsAmbientPropertyAvailable(String)

Queries whether a specified ambient property is available in the current scope.

(Inherited from FrameworkTemplate)
ISealable.Seal() ISealable.Seal() ISealable.Seal() ISealable.Seal() Inherited from FrameworkTemplate

Applies to

See Also