ControlTemplate 類別

定義

指定 Control 的視覺化結構和行為層面,其可透過控制項的多重執行個體 (Instance) 來共用。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
繼承
屬性

範例

以下顯示設定 ButtonControlTemplateButton StyleThe 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:

按鈕 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. 如需完整的範例,請參閱使用 ControlTemplate 設定樣式範例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)

請依一組規則來檢查樣版化父代 (Parent)。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)

查詢指定的環境屬性 (Ambient Property) 是否可用於目前的範圍。Queries whether a specified ambient property is available in the current scope.

(繼承來源 FrameworkTemplate)
ISealable.CanSeal (繼承來源 FrameworkTemplate)
ISealable.IsSealed (繼承來源 FrameworkTemplate)
ISealable.Seal() (繼承來源 FrameworkTemplate)

適用於

另請參閱