Aracılığıyla paylaş


Style Class

Definition

Contains property setters that can be shared between instances of a type. A Style is usually declared in a resources collection so that it can be shared and used for applying control templates and other styles.

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>
Inheritance
Object Platform::Object IInspectable DependencyObject Style
Attributes

Windows requirements

Device family
Windows 10 (introduced in 10.0.10240.0)
API contract
Windows.Foundation.UniversalApiContract (introduced in v1.0)

Examples

This example creates two styles: one for a TextBlock and one for a TextBox. Each style is applied to two instances of a control to create a uniform appearance for each TextBlock and TextBox. The example sets the FrameworkElement.Style property of each control by referencing the Style as a {StaticResource} markup extension. The example also shows how to retrieve a style from a resource dictionary and apply it to a control in code.

Each style has multiple Setter parts. In this XAML, no Style.Setters XAML property element appears. That is the typical usage in XAML for this property. The Style.Setters value is implicit, because Setters is the XAML content property for a Style. For more info on XAML syntax and how the XAML content syntax makes it possible to imply and omit certain XAML elements, see XAML syntax guide.

Notice that in the style for the TextBox, the Margin property is set to 4, which means that the TextBox has a margin of 4 on all sides. To compensate for the length of the second TextBlock, which is shorter than the first TextBlock because Last Name takes less room than First Name, a value of "6,4,4,4" is assigned to the Margin property on the second TextBox. This causes the second TextBox to have a different margin than what the style specifies, so that it aligns horizontally with the first 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);
}

This example creates two style elements. The TargetType for the first style element is set to TextBox and the TargetType for the second style element is set to Button. These are then applied as the implicit style for a TextBox control and a Button control.

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

This example creates a Style named InheritedStyle that is based on a Style named BaseStyle. InheritedStyle inherits the Background value of Yellow from BaseStyle and adds a Foreground value of 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>

Remarks

A Style is basically a collection of property settings applied to one or more instances of a particular type that has such properties. A Style contains a collection of one or more Setter objects. Each Setter has a Property and a Value. The Property is the name of the property of the element the style is applied to. The Value is the value that is applied to the property.

In order to apply a Style, the target object must be a DependencyObject. The property that each Setter references as a Property value must be a dependency property.

You must set the TargetType property when you create a Style. Otherwise an exception is thrown.

If you set a value for the same property in a Style and also on an element directly, the value set on the element directly takes precedence. For more info, see Dependency properties overview, specifically the "Dependency property value precedence" section.

Defining a Style as a XAML resource

A Style is almost always defined in XAML as a resource in a ResourceDictionary.

  • For a Style that is used only by other UI items defined in the same XAML page, you typically define the Style in the FrameworkElement.Resources collection (Page.Resources if your root element is a Page).
  • For a Style that is used by more than one page in your app, you typically define the Style in the Application.Resources collection. Alternatively, you might have a separate XAML file for the app that you include in Application.Resources as a MergedDictionaries value.
  • Most UI elements have a default style that's defined by the Windows Runtime. Copies of the default styles can be seen in the design-helper XAML file called generic.xaml, which isn't technically a resource file for apps although it's structured like one. You can copy discrete parts of this file into your app's XAML as the starting point when you edit copies of styles as enabled by the tools, but once you make such a copy it needs to be included in one of the Resources collections or indirectly accessed through MergedDictionaries. In all these cases the modified XAML that overrides the default is included as part of your app.

Windows 8 If you are re-templating an existing control in Windows 8 XAML, you sometimes modify the Style elements that exist in the StandardStyles.xaml XAML file that is included in most of the starting app templates. StandardStyles.xaml is referenced by the template app.xaml files as a MergedDictionaries source file. Templates for apps starting with Windows 8.1 don't use StandardStyles.xaml anymore.

A Style defined element in a ResourceDictionary is not required to have an x:Key attribute or x:Name attribute, which is normally a requirement of being a XAML resource. A Style that's defined this way uses its TargetType property value as the implicit key and is known as an implicit style.

For more info on how to use XAML resource dictionaries, see ResourceDictionary and XAML resource references.

Styles and templates

You can use a Setter in a Style to apply values to any dependency property. But it's the Setter for the Template property of a Control-derived class that constitutes the majority of the XAML markup in a typical Style. The Value for a Setter with Property="Template" is almost always specified as a property element that contains a ControlTemplate object element.

When a Style is used to define a control template, the TargetType of the Style element and the TargetType of the ControlTemplate element for its Control.Template setter should always use the same value.

The Template setter defines the basic template UI definition for a control instance where that template is applied. It also contains the visual states for a control, and other state-based UI definitions such as default theme transitions. For a complex control such as ListBox, the default template Style and the ControlTemplate within can have hundreds of lines of XAML. For more info on the role of Style in control templating scenarios, see XAML Control templates.

The template for a control often includes visual states that change the appearance of the control in response to logical states. For example, a Button can have a different visual appearance when it's pressed by applying a new visual state from its template, and all appearance changes can come from XAML not code. For more info on how visual states work and how to modify them or define states for custom controls, see Storyboarded animations for visual states and XAML Control templates.

Styles and runtime behavior

You can change the values of individual properties that have been set by a Style at run time and your new values overwrite the Setters values. For example, you can set the Template property at run time even if this property has been set by a style.

You can adjust the properties of a Style at run time, but only if that style hasn't been applied to anything, and only exists as a resource that's not being used implicitly. For example, you can add setters to the collection in Setters for a style that exists in Resources with an x:Key attribute but has no {StaticResource} markup extension value elsewhere in XAML that refers to that style. However, as soon as a Style is referenced and used for values by a loaded object, the Style should be considered sealed. You can detect the sealed state by checking the value of the IsSealed property for the Style. If it's true, then the style is sealed and you can't modify any properties of it or the Setter subvalues within. The point in time when a style's been put into use and sealed can also be detected when the object where the Style is referenced raises its Loaded event.

BasedOn styles

You can build a new style based on an existing style that's defined by your app or by default styles for Windows Runtime controls. You can do this using the BasedOn property. This reduces duplication in your XAML and makes it easier to manage resources. Each style supports only one BasedOn style. For more info, see BasedOn or Styling controls.

Implicit styles

You can define styles such that a Style is used implicitly by all objects of the same TargetType, without requiring each instance of such an object to specifically reference the Style as a FrameworkElement.Style value. When a <Style> resource is declared in a ResourceDictionary without an x:Key attribute, the x:Key value uses the value of the TargetType property. If you set the style implicitly, the style is applied only to the types that match the TargetType exactly and not to elements derived from the TargetType value. For example, if you create a style implicitly for all the ToggleButton controls in your application, and your application has ToggleButton and CheckBox controls (CheckBox derives from ToggleButton), the "ToggleButton" implicit style is applied only to the ToggleButton controls.

Notes on XAML syntax

Setters is the XAML content property for Style, so you can use an implicit collection syntax such as <Style><Setter .../><Setter .../></Style>.

Using the Style class in code (for example calling a constructor and building up the Setter values one by one) is very rare. Styles are used for templates, and templates should be available at XAML load time, so any Style created in code is usually available too late to be applied to controls in a UI.

Constructors

Style()

Initializes a new instance of the Style class, with no initial TargetType and an empty Setters collection.

Style(TypeName)

Initializes a new instance of the Style class, with a specified initial TargetType and an empty Setters collection.

Properties

BasedOn

Gets or sets a defined style that is the basis of the current style.

Dispatcher

Gets the CoreDispatcher that this object is associated with. The CoreDispatcher represents a facility that can access the DependencyObject on the UI thread even if the code is initiated by a non-UI thread.

(Inherited from DependencyObject)
IsSealed

Gets a value that indicates whether the style is read-only and cannot be changed.

Setters

Gets a collection of Setter objects.

TargetType

Gets or sets the type for which the style is intended. TargetType can be used to declare an implicit style resource if there's no resource key specified.

Methods

ClearValue(DependencyProperty)

Clears the local value of a dependency property.

(Inherited from DependencyObject)
GetAnimationBaseValue(DependencyProperty)

Returns any base value established for a dependency property, which would apply in cases where an animation is not active.

(Inherited from DependencyObject)
GetValue(DependencyProperty)

Returns the current effective value of a dependency property from a DependencyObject.

(Inherited from DependencyObject)
ReadLocalValue(DependencyProperty)

Returns the local value of a dependency property, if a local value is set.

(Inherited from DependencyObject)
RegisterPropertyChangedCallback(DependencyProperty, DependencyPropertyChangedCallback)

Registers a notification function for listening to changes to a specific DependencyProperty on this DependencyObject instance.

(Inherited from DependencyObject)
Seal()

Locks the style so that the TargetType property or any Setter in the Setters collection cannot be changed.

SetValue(DependencyProperty, Object)

Sets the local value of a dependency property on a DependencyObject.

(Inherited from DependencyObject)
UnregisterPropertyChangedCallback(DependencyProperty, Int64)

Cancels a change notification that was previously registered by calling RegisterPropertyChangedCallback.

(Inherited from DependencyObject)

Applies to

See also