ControlTemplate 类

定义

指定 Control 的可在其多个实例之间共享的可视结构和行为方面。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
继承
属性

示例

下面显示了一个 Button Style,用于设置 ButtonControlTemplateThe 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>

应用此应用时,Button 将显示为 EllipseWhen this gets applied, the Button appears as an Ellipse:

按钮 System.windows.controls.controltemplate> 示例Button ControlTemplate sample

如上例所示,将 ControlTemplate 属性设置为新的 ControlTemplate 时,将替换整个模板。When you set the Template property of a Control to a new ControlTemplate as in the above example, you are replacing the entire template. 当焦点或按下时,Button 是您要替换的按钮的默认外观的组成部分。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. 有关完整示例,请参阅使用 ControlTemplates 设置样式示例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.

注解

使用 ControlTemplate 可以指定控件的可视结构。The ControlTemplate allows you to specify the visual structure of a control. 控件作者可以定义默认 ControlTemplate,应用程序作者可以重写 ControlTemplate 以重新构造控件的可视结构。The control author can define the default ControlTemplate and the application author can override the ControlTemplate to reconstruct the visual structure of the control.

控件模板化是 WPFWPF 样式设置和模板化模型所提供的众多功能之一。Control templating is one of the many features offered by the WPFWPF 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. 如果你是想要更改控件的可视化效果或替换现有控件的 ControlTemplate 的应用程序作者,请参阅样式设置和模板化主题,了解示例和深入讨论。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.

ControlTemplate 旨在作为实现详细信息的自包含单元,该单元对外部用户和对象(包括样式)不可见。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 属性元素用法XAML Property Element Usage

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

XAML 值XAML Values

ControlTemplateControlTemplate
ControlTemplate 或派生类的对象元素。Object element for ControlTemplate or a derived class.

VisualTreeRootNodeVisualTreeRootNode
单个 XAMLXAML 元素作为 ControlTemplate (或派生类)的直接子级。A single XAMLXAML element as the immediate child of the ControlTemplate (or a derived class). 模板必须有一个根节点。Templates must have a single root node. 若要生成有用的模板,则选择为VisualTreeRootNode的元素应支持其自己的内容模型,通常是支持多个子元素的模型。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.

VisualTreeNodeContentsVisualTreeNodeContents
完成预期模板的一个或多个元素。One or more elements that complete the intended template. 如果选择为VisualTreeRootNode的元素仅支持单个子级,则只能有一个声明为VisualTreeNodeContents的元素。If the element chosen as VisualTreeRootNode only supports a single child, then there can only be one element declared as VisualTreeNodeContents. 如果所选的VisualTreeRootNode支持文本内容属性,还可能(但不常见)提供文本内容。It is also possible (though uncommon) to provide text content if the chosen VisualTreeRootNode supports a text content property.

构造函数

ControlTemplate()

初始化 ControlTemplate 类的新实例。Initializes a new instance of the ControlTemplate class.

ControlTemplate(Type)

使用指定的目标类型初始化 ControlTemplate 类的新实例。Initializes a new instance of the ControlTemplate class with the specified target type.

属性

Dispatcher

获取与此 Dispatcher 关联的 DispatcherObjectGets the Dispatcher this DispatcherObject is associated with.

(继承自 DispatcherObject)
HasContent

获取一个值,该值指示此模板是否具有优化内容。Gets a value that indicates whether this template has optimized content.

(继承自 FrameworkTemplate)
IsSealed

获取一个值,该值指示此对象是否处于不可变状态,如果处于该状态则无法更改对象。Gets a value that indicates whether this object is in an immutable state so it cannot be changed.

(继承自 FrameworkTemplate)
Resources

获取或设置可在此模板范围内使用的资源集合。Gets or sets the collection of resources that can be used within the scope of this template.

(继承自 FrameworkTemplate)
TargetType

获取或设置此 ControlTemplate 所针对的类型。Gets or sets the type for which this ControlTemplate is intended.

Template

获取或设置一个引用,该引用指向当编写器定义或应用模板时用于录制或播放模板的 XAML 节点的对象。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.

(继承自 FrameworkTemplate)
Triggers

获取根据指定条件应用属性更改或执行操作的 TriggerBase 对象的集合。Gets a collection of TriggerBase objects that apply property changes or perform actions based on specified conditions.

VisualTree

获取或设置模板的根节点。Gets or sets the root node of the template.

(继承自 FrameworkTemplate)

方法

CheckAccess()

确定调用线程是否可以访问此 DispatcherObjectDetermines whether the calling thread has access to this DispatcherObject.

(继承自 DispatcherObject)
Equals(Object)

确定指定的对象是否等于当前对象。Determines whether the specified object is equal to the current object.

(继承自 Object)
FindName(String, FrameworkElement)

查找与此模板中定义的指定名称关联的元素。Finds the element associated with the specified name defined within this template.

(继承自 FrameworkTemplate)
GetHashCode()

作为默认哈希函数。Serves as the default hash function.

(继承自 Object)
GetType()

获取当前实例的 TypeGets the Type of the current instance.

(继承自 Object)
LoadContent()

将模板的内容加载为对象的实例,并返回该内容的根元素。Loads the content of the template as an instance of an object and returns the root element of the content.

(继承自 FrameworkTemplate)
MemberwiseClone()

创建当前 Object 的浅表副本。Creates a shallow copy of the current Object.

(继承自 Object)
RegisterName(String, Object)

将新的名称/对象对注册到当前名称范围内。Registers a new name/object pair into the current name scope.

(继承自 FrameworkTemplate)
Seal()

锁定模板,使其无法更改。Locks the template so it cannot be changed.

(继承自 FrameworkTemplate)
ShouldSerializeResources(XamlDesignerSerializationManager)

返回一个值,该值指示序列化过程是否应序列化此类的实例上的 Resources 属性值。Returns a value that indicates whether serialization processes should serialize the value of the Resources property on instances of this class.

(继承自 FrameworkTemplate)
ShouldSerializeVisualTree()

返回一个值,该值指示序列化过程是否应序列化此类的实例上的 VisualTree 属性值。Returns a value that indicates whether serialization processes should serialize the value of the VisualTree property on instances of this class.

(继承自 FrameworkTemplate)
ToString()

返回表示当前对象的字符串。Returns a string that represents the current object.

(继承自 Object)
UnregisterName(String)

从 XAML 名称范围中移除名称/对象映射。Removes a name/object mapping from the XAML namescope.

(继承自 FrameworkTemplate)
ValidateTemplatedParent(FrameworkElement)

根据一组规则检查模板化父级。Checks the templated parent against a set of rules.

VerifyAccess()

强制调用线程具有此 DispatcherObject 的访问权限。Enforces that the calling thread has access to this DispatcherObject.

(继承自 DispatcherObject)

显式接口实现

INameScope.FindName(String)

返回具有提供的标识名称的对象。Returns an object that has the provided identifying name.

(继承自 FrameworkTemplate)
IQueryAmbient.IsAmbientPropertyAvailable(String)

查询当前范围中是否有指定的环境属性。Queries whether a specified ambient property is available in the current scope.

(继承自 FrameworkTemplate)

适用于

另请参阅