Export (0) Print
Expand All

ControlTemplate Class

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

Namespace:  System.Windows.Controls
Assembly:  PresentationFramework (in PresentationFramework.dll)
XMLNS for XAML: http://schemas.microsoft.com/winfx/2006/xaml/presentation, http://schemas.microsoft.com/netfx/2007/xaml/presentation

[DictionaryKeyPropertyAttribute("TargetType")]
[LocalizabilityAttribute(LocalizationCategory.None, Readability = Readability.Unreadable)]
public class ControlTemplate : FrameworkTemplate
<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.

The ControlTemplate type exposes the following members.

  NameDescription
Public methodControlTemplate()Initializes a new instance of the ControlTemplate class.
Public methodControlTemplate(Type)Initializes a new instance of the ControlTemplate class with the specified target type.
Top

  NameDescription
Public propertyDispatcherGets the Dispatcher this DispatcherObject is associated with. (Inherited from DispatcherObject.)
Public propertyHasContentGets a value that indicates whether this template has optimized content. (Inherited from FrameworkTemplate.)
Public propertyIsSealedGets a value that indicates whether this object is in an immutable state so it cannot be changed. (Inherited from FrameworkTemplate.)
Public propertyResourcesGets or sets the collection of resources that can be used within the scope of this template. (Inherited from FrameworkTemplate.)
Public propertyTargetTypeGets or sets the type for which this ControlTemplate is intended.
Public propertyTemplateGets 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.)
Public propertyTriggersGets a collection of TriggerBase objects that apply property changes or perform actions based on specified conditions.
Public propertyVisualTreeGets or sets the root node of the template. (Inherited from FrameworkTemplate.)
Top

  NameDescription
Public methodCheckAccessDetermines whether the calling thread has access to this DispatcherObject. (Inherited from DispatcherObject.)
Public methodEquals(Object)Determines whether the specified Object is equal to the current Object. (Inherited from Object.)
Protected methodFinalizeAllows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public methodFindNameFinds the element associated with the specified name defined within this template. (Inherited from FrameworkTemplate.)
Public methodGetHashCodeServes as a hash function for a particular type. (Inherited from Object.)
Public methodGetTypeGets the Type of the current instance. (Inherited from Object.)
Public methodLoadContentLoads the content of the template as an instance of an object and returns the root element of the content. (Inherited from FrameworkTemplate.)
Protected methodMemberwiseCloneCreates a shallow copy of the current Object. (Inherited from Object.)
Public methodRegisterNameRegisters a new name/object pair into the current name scope. (Inherited from FrameworkTemplate.)
Public methodSealLocks the template so it cannot be changed. (Inherited from FrameworkTemplate.)
Public methodShouldSerializeResourcesReturns a value that indicates whether serialization processes should serialize the value of the Resources property on instances of this class. (Inherited from FrameworkTemplate.)
Public methodShouldSerializeVisualTreeReturns a value that indicates whether serialization processes should serialize the value of the VisualTree property on instances of this class. (Inherited from FrameworkTemplate.)
Public methodToStringReturns a string that represents the current object. (Inherited from Object.)
Public methodUnregisterNameRemoves a name/object mapping from the XAML namescope. (Inherited from FrameworkTemplate.)
Protected methodValidateTemplatedParentChecks the templated parent against a set of rules. (Overrides FrameworkTemplate.ValidateTemplatedParent(FrameworkElement).)
Public methodVerifyAccessEnforces that the calling thread has access to this DispatcherObject. (Inherited from DispatcherObject.)
Top

  NameDescription
Explicit interface implemetationPrivate methodINameScope.FindNameInfrastructure. Returns an object that has the provided identifying name. (Inherited from FrameworkTemplate.)
Explicit interface implemetationPrivate methodIQueryAmbient.IsAmbientPropertyAvailableQueries whether a specified ambient property is available in the current scope. (Inherited from FrameworkTemplate.)
Top

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.

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.

.NET Framework

Supported in: 4, 3.5, 3.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows Server 2008 (Server Core not supported), Windows Server 2008 R2 (Server Core supported with SP1 or later), Windows Server 2003 SP2

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

Community Additions

ADD
Show:
© 2014 Microsoft