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 ,用于设置ControlTemplateButton: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>

在应用它后,Button显示为Ellipse:When this gets applied, the Button appears as an Ellipse:

按钮 ControlTemplate 示例Button ControlTemplate sample

当您将设置Template的属性Control到一个新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仅支持单个子级,然后那里可以仅将一个元素声明为VisualTreeNodeContentsIf 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)
ISealable.CanSeal (继承自 FrameworkTemplate)
ISealable.IsSealed (继承自 FrameworkTemplate)
ISealable.Seal() (继承自 FrameworkTemplate)

适用于

另请参阅