ControlTemplate ControlTemplate ControlTemplate ControlTemplate Class

定義

指定 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
繼承
屬性

範例

下列所示ButtonStyle如此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:

Button ControlTemplate 範例Button ControlTemplate sample

當您設定Template的屬性ControlControlTemplate如同上述範例中,您要取代整個範本。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.

AControlTemplate將不會察覺到外部使用者和物件,包括樣式的實作詳細資料的自主的單位。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() ControlTemplate() ControlTemplate()

初始化 ControlTemplate 類別的新執行個體。Initializes a new instance of the ControlTemplate class.

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

使用指定的目標型別來初始化 ControlTemplate 類別的新執行個體。Initializes a new instance of the ControlTemplate class with the specified target type.

屬性

Dispatcher Dispatcher Dispatcher Dispatcher

取得與這個 Dispatcher 關聯的 DispatcherObjectGets 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

為預期為 ControlTemplate 的項目取得或設定類型。Gets or sets the type for which this ControlTemplate is intended.

Template Template Template 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.

(Inherited from FrameworkTemplate)
Triggers Triggers Triggers Triggers

取得 TriggerBase 物件的集合,其會根據指定的條件套用屬性變更,或執行動作。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)

方法

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

判斷呼叫的執行是否可以存取這個 DispatcherObjectDetermines 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()

取得目前執行個體的 TypeGets 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()

建立目前 Object 的淺層複本 (Shallow Copy)。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)

傳回值,這個值表示在這個類別的執行個體上,序列化處理是否應該將 Resources 屬性的值序列化。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()

傳回值,這個值表示在這個類別的執行個體上,序列化處理是否應該將 VisualTree 屬性的值序列化。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)

從 XAML 名稱範圍移除名稱/物件對應。Removes a name/object mapping from the XAML namescope.

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

請依一組規則來檢查樣版化父代 (Parent)。Checks the templated parent against a set of rules.

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

請強制執行可以存取這個 DispatcherObject 的呼叫執行緒。Enforces that the calling thread has access to this DispatcherObject.

(Inherited from DispatcherObject)

明確介面實作

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)

查詢指定的環境屬性 (Ambient Property) 是否可用於目前的範圍。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

適用於

另請參閱