Style class

Applies to Windows and Windows Phone

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.

Inheritance

Object
  DependencyObject
    Style

Syntax


public sealed class Style : DependencyObject


<Style .../>
-or-
<Style ...>
  oneOrMoreSetters
</Style>

XAML Values

oneOrMoreSetters

One or more Setter object elements.

Attributes

[ContentProperty("Name=Setters")]
[MarshalingBehavior(Agile)]
[Threading(Both)]
[Version(0x06020000)]
[WebHostHidden()]

Members

The Style class has these types of members:

Constructors

The Style class has these constructors.

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

 

Methods

The Style class has these methods. It also inherits methods from the Object class.

MethodDescription
ClearValue Clears the local value of a dependency property. (Inherited from DependencyObject)
GetAnimationBaseValue Returns any base value established for a dependency property, which would apply in cases where an animation is not active. (Inherited from DependencyObject)
GetValue Returns the current effective value of a dependency property from a DependencyObject. (Inherited from DependencyObject)
ReadLocalValue Returns the local value of a dependency property, if a local value is set. (Inherited from DependencyObject)
Seal Locks the style so that the TargetType property or any Setter in the Setters collection cannot be changed.
SetValue Sets the local value of a dependency property on a DependencyObject. (Inherited from DependencyObject)

 

Properties

The Style class has these properties.

PropertyAccess typeDescription

BasedOn

Read/writeGets or sets a defined style that is the basis of the current style.

Dispatcher

Read-onlyGets the CoreDispatcher that this object is associated with. (Inherited from DependencyObject)

IsSealed

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

Setters

Read-onlyGets a collection of Setter objects.

TargetType

Read/writeGets 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.

 

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 Quickstart: 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 Quickstart: 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 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 Quickstart: 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.

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.

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>
  <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 TextBlock that specifies that
              the Width is 200, Height is 20, 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 Style="{StaticResource TextBlockStyle}">
              First Name:
          </TextBlock>
    <TextBox Style="{StaticResource TextBoxStyle}"/>
  </StackPanel>
  <StackPanel Orientation="Horizontal">
    <TextBlock Style="{StaticResource TextBlockStyle}">
              Last Name:
          </TextBlock>
    <TextBox Style="{StaticResource TextBoxStyle}"  
                   Margin="6,4,4,4"/>
  </StackPanel>
</StackPanel>


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


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


Requirements

Minimum supported client

Windows 8 [Windows Store apps only]

Minimum supported server

Windows Server 2012 [Windows Store apps only]

Minimum supported phone

Windows Phone 8.1 [Windows Runtime apps only]

Namespace

Windows.UI.Xaml
Windows::UI::Xaml [C++]

Metadata

Windows.winmd

See also

DependencyObject
ControlTemplate
Setter
Dependency properties overview
ResourceDictionary and XAML resource references
Quickstart: Styling controls
Quickstart: Control templates

 

 

Show:
© 2014 Microsoft