Style 類別

定義

包含可在類型實例之間共用的屬性 setter。 樣式通常會在資源集合中宣告,以便共用並用於套用控制項範本和其他樣式。

public ref class Style sealed : DependencyObject
/// [Windows.Foundation.Metadata.Activatable(Windows.UI.Xaml.IStyleFactory, 65536, Windows.Foundation.UniversalApiContract)]
/// [Windows.Foundation.Metadata.Activatable(65536, Windows.Foundation.UniversalApiContract)]
/// [Windows.Foundation.Metadata.ContractVersion(Windows.Foundation.UniversalApiContract, 65536)]
/// [Windows.Foundation.Metadata.MarshalingBehavior(Windows.Foundation.Metadata.MarshalingType.Agile)]
/// [Windows.Foundation.Metadata.Threading(Windows.Foundation.Metadata.ThreadingModel.Both)]
/// [Windows.UI.Xaml.Markup.ContentProperty(Name="Setters")]
class Style final : DependencyObject
/// [Windows.Foundation.Metadata.ContractVersion(Windows.Foundation.UniversalApiContract, 65536)]
/// [Windows.Foundation.Metadata.MarshalingBehavior(Windows.Foundation.Metadata.MarshalingType.Agile)]
/// [Windows.Foundation.Metadata.Threading(Windows.Foundation.Metadata.ThreadingModel.Both)]
/// [Windows.UI.Xaml.Markup.ContentProperty(Name="Setters")]
/// [Windows.Foundation.Metadata.Activatable(65536, "Windows.Foundation.UniversalApiContract")]
/// [Windows.Foundation.Metadata.Activatable(Windows.UI.Xaml.IStyleFactory, 65536, "Windows.Foundation.UniversalApiContract")]
class Style final : DependencyObject
[Windows.Foundation.Metadata.Activatable(typeof(Windows.UI.Xaml.IStyleFactory), 65536, typeof(Windows.Foundation.UniversalApiContract))]
[Windows.Foundation.Metadata.Activatable(65536, typeof(Windows.Foundation.UniversalApiContract))]
[Windows.Foundation.Metadata.ContractVersion(typeof(Windows.Foundation.UniversalApiContract), 65536)]
[Windows.Foundation.Metadata.MarshalingBehavior(Windows.Foundation.Metadata.MarshalingType.Agile)]
[Windows.Foundation.Metadata.Threading(Windows.Foundation.Metadata.ThreadingModel.Both)]
[Windows.UI.Xaml.Markup.ContentProperty(Name="Setters")]
public sealed class Style : DependencyObject
[Windows.Foundation.Metadata.ContractVersion(typeof(Windows.Foundation.UniversalApiContract), 65536)]
[Windows.Foundation.Metadata.MarshalingBehavior(Windows.Foundation.Metadata.MarshalingType.Agile)]
[Windows.Foundation.Metadata.Threading(Windows.Foundation.Metadata.ThreadingModel.Both)]
[Windows.UI.Xaml.Markup.ContentProperty(Name="Setters")]
[Windows.Foundation.Metadata.Activatable(65536, "Windows.Foundation.UniversalApiContract")]
[Windows.Foundation.Metadata.Activatable(typeof(Windows.UI.Xaml.IStyleFactory), 65536, "Windows.Foundation.UniversalApiContract")]
public sealed class Style : DependencyObject
Public NotInheritable Class Style
Inherits DependencyObject
<Style .../>
-or-
<Style ...>
  oneOrMoreSetters
</Style>
繼承
Object Platform::Object IInspectable DependencyObject Style
屬性

Windows 需求

裝置系列
Windows 10 (已於 10.0.10240.0 引進)
API contract
Windows.Foundation.UniversalApiContract (已於 v1.0 引進)

範例

此範例會建立兩個樣式:一個用於 TextBlock ,另一個用於 TextBox。 每個樣式都會套用至控制項的兩個實例,以為每個 TextBlockTextBox建立統一的外觀。 此範例會將 Style 參考為{StaticResource} 標記延伸,以設定每個控制項的FrameworkElement.Style屬性。 此範例也會示範如何從資源字典擷取樣式,並將其套用至程式碼中的控制項。

每個樣式都有多個 Setter 元件。 在此 XAML 中,不會顯示 XAML Style.Setters 屬性專案。 這是這個屬性之 XAML 中的一般用法。 值 Style.Setters 是隱含的,因為 Setters 是 Style 的 XAML 內容屬性。 如需 XAML 語法以及如何讓 XAML 內容語法能夠隱含和省略特定 XAML 元素的詳細資訊,請參閱 XAML 語法指南

請注意,在 TextBox的樣式中, Margin 屬性會設定為 4,這表示 TextBox 在所有邊都有 4 的邊界。 為了補償第二個TextBlock的長度,其長度比第一個TextBlock短,因為姓氏取用的空間小於名字,則會在第二個TextBox上將值 「6,4,4,4」「 指派給Margin屬性。 這會導致第二個 TextBox 的邊界與樣式所指定的邊界不同,以便水準對齊第一個 TextBox

<StackPanel x:Name="rootPanel">
  <StackPanel.Resources>
    <!--Create a Style for a TextBlock to specify that the
              Foreground equals Navy, FontSize equals 14, and
              VerticalAlignment equals Botton.-->
    <Style TargetType="TextBlock" x:Key="TextBlockStyle">
      <Setter Property="Foreground" Value="Navy"/>
      <Setter Property="FontSize" Value="14"/>
      <Setter Property="VerticalAlignment" Value="Bottom"/>
    </Style>

    <!--Create a Style for a TextBox that specifies that
              the Width is 200, Height is 30, Margin is 4,
              Background is LightBlue, and FontSize is 14.-->
    <Style TargetType="TextBox" x:Key="TextBoxStyle">
      <Setter Property="Width" Value="200"/>
      <Setter Property="Height" Value="30"/>
      <Setter Property="Margin" Value="4"/>
      <Setter Property="FontSize" Value="14"/>
      <Setter Property="Background">
        <Setter.Value>
          <LinearGradientBrush StartPoint="0,0.5" EndPoint="1,0.5">
            <GradientStop Color="White" Offset="0.0"/>
            <GradientStop Color="LightBlue" Offset="0.5"/>
            <GradientStop Color="Navy" Offset="1"/>
          </LinearGradientBrush>
        </Setter.Value>
      </Setter>
    </Style>
  </StackPanel.Resources>

  <!--Apply the TextBlockStyle and TextBoxStyle to each 
      TextBlock and TextBox, respectively.-->
  <StackPanel Orientation="Horizontal">
    <TextBlock Text="First Name:" Style="{StaticResource TextBlockStyle}"/>
    <TextBox Style="{StaticResource TextBoxStyle}"/>
  </StackPanel>
  <StackPanel Orientation="Horizontal">
    <TextBlock Text="Last Name:" Style="{StaticResource TextBlockStyle}"/>
    <TextBox Style="{StaticResource TextBoxStyle}"
             Margin="6,4,4,4"/>
  </StackPanel>
  <StackPanel x:Name="emailAddressPanel" Orientation="Horizontal"/>
</StackPanel>
private void ShowEmailAddressBox()
{
    TextBlock emailAddressLabel = new TextBlock();
    emailAddressLabel.Text = "Email:";
    emailAddressLabel.Style = (Style)rootPanel.Resources["TextBlockStyle"];

    TextBox emailAddressBox = new TextBox();
    emailAddressBox.Style = (Style)rootPanel.Resources["TextBoxStyle"];
    emailAddressBox.Margin = new Thickness(38, 4, 4, 4);

    emailAddressPanel.Children.Add(emailAddressLabel);
    emailAddressPanel.Children.Add(emailAddressBox);
}

此範例會建立兩個樣式專案。 第一個樣式專案的 TargetType 設定為 TextBox,而第二個樣式專案的 TargetType 會設定為 Button。 然後,這些會套用為 TextBox 控制項和 Button 控制項的隱含樣式。

<StackPanel>
    <StackPanel.Resources>
        <Style TargetType="TextBox">
            <Setter Property="Foreground" Value="Pink" />
            <Setter Property="FontSize" Value="15" />                
        </Style>
        
        <Style TargetType="Button">
            <Setter Property="Foreground" Value="Black" />
            <Setter Property="Background" Value="Yellow" />
        </Style>
    </StackPanel.Resources>
    
    <TextBox Height="30" Width="120" Margin="2" Text="TextBoxStyle" />
    <Button Height="30" Width="100" Margin="2" Content="ButtonStyle" />
</StackPanel>

此範例會根據名為 BaseStyle 的 Style 建立名為 InheritedStyle 的 Style。 InheritedStyle 會從 BaseStyle 繼承 Yellow 的背景值,並新增 Red 的前景值。

<StackPanel>
    <StackPanel.Resources>
        <Style x:Key="BaseStyle" TargetType="Button">
            <Setter Property="Background" Value="Yellow" />
        </Style>
        <!--Create a Style based on BaseStyle-->
        <Style x:Key="InheritedStyle" TargetType="Button" BasedOn="{StaticResource BaseStyle}">
            <Setter Property="Foreground" Value="Red" />
        </Style>
    </StackPanel.Resources>
    <!--A button with default style-->
    <Button Content="HelloWorld" />
    <!--A button with base style-->
    <Button Content="HelloWorld" Style="{StaticResource BaseStyle}" />
    <!--A button with a style that is inherited from the BaseStyle-->
    <Button Content="HelloWorld" Style="{StaticResource InheritedStyle}" />
</StackPanel>

備註

Style 基本上是套用至具有這類屬性之特定類型的一或多個實例的屬性設定集合。 Style 包含一或多個 Setter 物件的集合。 每個 Setter 都有 PropertyValueProperty是套用樣式的專案屬性名稱。 Value是套用至 屬性的值。

若要套用 Style,目標物件必須是 DependencyObject。 每個 Setter 參考做為 屬性值 的屬性都必須是相依性屬性。

當您建立 Style 時,必須設定 TargetType 屬性。 否則,會擲回例外狀況。

如果您在 Style 中設定相同屬性的值,也直接在元素上設定值,則直接在元素上設定的值會優先。 如需詳細資訊,請參閱 相依性屬性概觀,特別是一節。

樣式 定義為 XAML 資源

Style 幾乎一律在 XAML 中定義為 ResourceDictionary中的資源。

  • 對於只有相同 XAML 頁面中定義之其他 UI 專案使用的 Style,如果您的根項目是Page) ,您通常會在FrameworkElement.Resources集合 Page.Resources 中定義 Style (。
  • 針對應用程式中多個頁面使用的 Style,您通常會在 Application.Resources 集合中定義 Style。 或者,您可能為 Application.Resources 中包含的應用程式提供個別的 XAML 檔案,做為 MergedDictionaries 值。
  • 大部分的 UI 元素都有Windows 執行階段所定義的預設樣式。 預設樣式的複本可以在名為 generic.xaml 的設計協助程式 XAML 檔案中看到,雖然其結構就像一樣,但不是應用程式的資源檔。 當您編輯由工具啟用的樣式複本時,您可以將此檔案的離散部分複製到應用程式的 XAML 中,但一旦製作這類複本,它就必須包含在其中一個 Resources 集合中,或透過 MergedDictionaries間接存取。 在這些情況下,覆寫預設值的已修改 XAML 會包含在您的應用程式中。

Windows 8 如果您要在 Windows 8 XAML 中重新範本化現有的控制項,您有時會修改 StandardStyles.xaml XAML 檔案中存在的 Style 元素,而該檔案包含在大部分的起始應用程式範本中。 StandardStyles.xaml 是由範本 app.xaml 檔案參考為 MergedDictionaries 來源檔案。 從 Windows 8.1 開始的應用程式範本不再使用 StandardStyles.xaml。

ResourceDictionary中的 Style 定義元素不需要有x:Key 屬性x:Name 屬性,這通常是 XAML 資源的需求。 以這種方式定義的 Style 會使用 其 TargetType 屬性值作為隱含索引鍵,稱為隱含樣式。

如需如何使用 XAML 資源字典的詳細資訊,請參閱 ResourceDictionary 和 XAML 資源參考

樣式及範本

您可以使用 Style 中的 Setter ,將值套用至任何相依性屬性。 但它是Control衍生類別之Template屬性的Setter,其構成一般 Style 中大部分的 XAML 標記。 SetterProperty="Template"Value幾乎一律指定為包含ControlTemplate物件元素的屬性專案。

使用 Style 來定義控制項範本時,Style 元素的TargetType及其Control.Template setter的 ControlTemplate元素TargetType應該一律使用相同的值。

Template setter 會定義套用該範本之控制項實例的基本範本 UI 定義。 它也包含控制項的視覺狀態,以及其他以狀態為基礎的 UI 定義,例如預設主題轉換。 對於 ListBox之類的複雜控制項,內的預設範本 Style 和 ControlTemplate 可以有數百行 XAML。 如需控制項範本化案例中 Style 角色的詳細資訊,請參閱 XAML 控制項範本

控制項的範本通常包含視覺狀態,這些狀態會變更控制項的外觀,以回應邏輯狀態。 例如, 當按鈕 透過從範本套用新的視覺狀態來按下按鈕時,可能會有不同的視覺外觀,而且所有外觀變更都可以來自 XAML 而非程式碼。 如需視覺狀態如何運作以及如何修改或定義自訂控制項狀態的詳細資訊,請參閱視覺狀態和XAML 控制項範本的腳本動畫

樣式和執行時間行為

您可以變更在執行時間由 Style 設定的個別屬性值,而您的新值會覆寫 Setters 值。 例如,即使這個屬性已由樣式設定,您也可以在執行時間設定 Template 屬性。

您可以在執行時間調整 Style 的屬性,但只有在該樣式尚未套用至任何專案時,且只存在為未隱含使用的資源。 例如,您可以將setter 新增至 Setters中具有x:Key 屬性資源中的樣式集合,但 XAML 中沒有參考該樣式的{StaticResource} 標記延伸值。 不過,一旦參考 Style 並用於載入物件的值時,Style 就應該視為密封。 您可以檢查 Style 的 IsSealed 屬性值,以偵測密封狀態。 如果為 true,則樣式會密封,而且您無法修改它的任何屬性或中的 Setter 子值。 當參考 Style 的物件引發 其 Loaded 事件時,也可以偵測到樣式已使用且密封的時間點。

BasedOn 樣式

您可以根據應用程式所定義的現有樣式或預設Windows 執行階段控制項的樣式來建置新的樣式。 您可以使用 BasedOn 屬性來執行此動作。 這可減少 XAML 中的重複,並讓您更輕鬆地管理資源。 每個樣式僅支援一個 BasedOn 樣式。 如需詳細資訊,請參閱 BasedOn設定控制項樣式

隱含樣式

您可以定義樣式,讓相同 TargetType的所有物件隱含使用 Style,而不需要這類物件的每個實例將 Style 特別參考為 FrameworkElement.Style 值。 <Style>在沒有x:Key 屬性ResourceDictionary中宣告資源時,x:Key值會使用TargetType屬性的值。 如果您隱含設定樣式,樣式只會套用至完全符合 TargetType 的類型,而不是套用至衍生自 TargetType 值的元素。 例如,如果您隱含建立應用程式中所有ToggleButton控制項的樣式,而且您的應用程式具有ToggleButtonCheckBox 控制項, (CheckBox衍生自ToggleButton) ,則 「ToggleButton」 隱含樣式只會套用至ToggleButton控制項。

XAML 語法的注意事項

Setter 是 Style 的 XAML 內容屬性,因此您可以使用隱含集合語法,例如 <Style><Setter .../><Setter .../></Style>

例如,在程式碼中使用 Style 類別 (例如呼叫建構函式,並逐一建置 Setter 值) 非常罕見。 樣式用於範本,而且範本應在 XAML 載入時使用,因此在程式碼中建立的任何樣式通常都太晚,無法套用至 UI 中的控制項。

建構函式

Style()

初始化 Style 類別的新實例,沒有初始 TargetType 和空 的 Setters 集合。

Style(TypeName)

使用指定的初始TargetType和空的 Setters集合,初始化Style類別的新實例。

屬性

BasedOn

取得或設定做為目前樣式之基礎的已定義樣式。

Dispatcher

取得這個 物件相關聯的 CoreDispatcherCoreDispatcher代表可在 UI 執行緒上存取DependencyObject的功能,即使程式碼是由非 UI 執行緒起始也一樣。

(繼承來源 DependencyObject)
IsSealed

取得值,這個值表示樣式是否為唯讀而無法加以變更。

Setters

取得 Setter 物件的集合。

TargetType

取得或設定樣式的預定型別。 如果沒有指定資源索引鍵,則 TargetType 可用來宣告隱含樣式資源。

方法

ClearValue(DependencyProperty)

清除相依性屬性的本機值。

(繼承來源 DependencyObject)
GetAnimationBaseValue(DependencyProperty)

傳回為相依性屬性建立的任何基底值,如果動畫未使用中,則適用此屬性。

(繼承來源 DependencyObject)
GetValue(DependencyProperty)

DependencyObject傳回相依性屬性的目前有效值。

(繼承來源 DependencyObject)
ReadLocalValue(DependencyProperty)

如果已設定本機值,則傳回相依性屬性的本機值。

(繼承來源 DependencyObject)
RegisterPropertyChangedCallback(DependencyProperty, DependencyPropertyChangedCallback)

註冊通知函式,以接聽此DependencyObject實例上特定DependencyProperty的變更。

(繼承來源 DependencyObject)
Seal()

鎖定樣式,以便無法變更Setters集合中的TargetType屬性或任何Setter

SetValue(DependencyProperty, Object)

設定 DependencyObject上相依性屬性的本機值。

(繼承來源 DependencyObject)
UnregisterPropertyChangedCallback(DependencyProperty, Int64)

取消先前透過呼叫 RegisterPropertyChangedCallback註冊的變更通知。

(繼承來源 DependencyObject)

適用於

另請參閱