共用方式為


Style Class

Microsoft Silverlight will reach end of support after October 2021. Learn more.

Contains property setters that can be shared between instances of a type.

Inheritance Hierarchy

System.Object
  System.Windows.DependencyObject
    System.Windows.Style

Namespace:  System.Windows
Assembly:  System.Windows (in System.Windows.dll)

Syntax

'Declaration
<ContentPropertyAttribute("Setters", True)> _
Public NotInheritable Class Style _
    Inherits DependencyObject
[ContentPropertyAttribute("Setters", true)]
public sealed class Style : DependencyObject
<Style .../>
-or-
<Style ...>
  oneOrMoreSetters
</Style>

XAML Values

  • oneOrMoreSetters
    One or more object elements for objects that derive from SetterBase. Generally, these are Setter object elements.

The Style type exposes the following members.

Constructors

  Name Description
Public methodSupported by Silverlight for Windows Phone Style() Initializes a new instance of the Style class.
Public methodSupported by Silverlight for Windows Phone Style(Type) Initializes a new instance of the Style class to use on the specified Type.

Top

Properties

  Name Description
Public propertySupported by Silverlight for Windows Phone BasedOn Gets or sets a defined style that is the basis of the current style.
Public propertySupported by Silverlight for Windows Phone Dispatcher Gets the Dispatcher this object is associated with. (Inherited from DependencyObject.)
Public propertySupported by Silverlight for Windows Phone IsSealed Gets a value that indicates whether the style is read-only and cannot be changed.
Public propertySupported by Silverlight for Windows Phone Setters Gets a collection of Setter objects.
Public propertySupported by Silverlight for Windows Phone TargetType Gets or sets the type for which the style is intended.

Top

Methods

  Name Description
Public methodSupported by Silverlight for Windows Phone CheckAccess Determines whether the calling thread has access to this object. (Inherited from DependencyObject.)
Public methodSupported by Silverlight for Windows Phone ClearValue Clears the local value of a dependency property. (Inherited from DependencyObject.)
Public methodSupported by Silverlight for Windows Phone Equals(Object) Determines whether the specified Object is equal to the current Object. (Inherited from Object.)
Protected methodSupported by Silverlight for Windows Phone Finalize Allows an object to try to free resources and perform other cleanup operations before the Object is reclaimed by garbage collection. (Inherited from Object.)
Public methodSupported by Silverlight for Windows Phone GetAnimationBaseValue Returns any base value established for a Silverlight dependency property, which would apply in cases where an animation is not active. (Inherited from DependencyObject.)
Public methodSupported by Silverlight for Windows Phone GetHashCode Serves as a hash function for a particular type. (Inherited from Object.)
Public methodSupported by Silverlight for Windows Phone GetType Gets the Type of the current instance. (Inherited from Object.)
Public methodSupported by Silverlight for Windows Phone GetValue Returns the current effective value of a dependency property from a DependencyObject. (Inherited from DependencyObject.)
Protected methodSupported by Silverlight for Windows Phone MemberwiseClone Creates a shallow copy of the current Object. (Inherited from Object.)
Public methodSupported by Silverlight for Windows Phone ReadLocalValue Returns the local value of a dependency property, if a local value is set. (Inherited from DependencyObject.)
Public methodSupported by Silverlight for Windows Phone Seal Locks the style so that the TargetType property or any Setter in the Setters collection cannot be changed.
Public methodSupported by Silverlight for Windows Phone SetValue Sets the local value of a dependency property on a DependencyObject. (Inherited from DependencyObject.)
Public methodSupported by Silverlight for Windows Phone ToString Returns a string that represents the current object. (Inherited from Object.)

Top

Remarks

A Style is basically a collection of property settings applied to multiple instances of the same type. 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.

NoteNote:

If there is more than one setter in the setter collection with the same Property value, the setter that is declared last is used. Similarly, if you set a value for the same property in a style and on an element directly, the value set on the element directly takes precedence.

You can set a Style on any element that derives from FrameworkElement. A style is most commonly declared with the x:Key attribute as a resource inside the Resources section in a XAML file and then referenced as a StaticResource. Because styles are resources, they obey the same scoping rules that apply to all resources, so where you declare a style affects where it can be applied. For example, if you declare the style in the root element of your application definition XAML file, the style can be used anywhere in your application.

You must set the TargetType property when you create a Style. If you do not, an exception is thrown.

You can change the values of individual properties that have been set within a style. For example, you can set the Template property at run time even if this property has been set by a style. Or you can add setters to the collection in Setters. However, as soon as that style is put into use by a loaded object, the Style should be considered sealed. You can detect this state by checking the value of IsSealed property for the Style. A style is considered to be in use as soon as it is referenced by a loaded object that is connected to the object tree and the Silverlight root visual. This point in time can be detected when the object where the Style property is set raises its Loaded event.

Starting with Silverlight 3, the write-once limitation on the FrameworkElement.Style property is removed. You can set the FrameworkElement.Style property to override a built-in default style. Setting the same style multiple times will not result in an exception.

To assign a named style to an element programmatically, get the style from the resources collection and assign it to the element's FrameworkElement.Style property. Note that the items in a resources collection are of the type Object, so you must cast the retrieved style to a Style object before assigning it to the FrameworkElement.Style property. For example, to set the defined TitleText style on a TextBlock named textblock1, do the following:

textblock1.Style = (Style)(this.Resources["TitleText"]);
textblock1.Style = DirectCast((Me.Resources("TitleText")), Style)

Implicit Styles

In Silverlight 4, you can set styles implicitly. That is, you can apply a certain style to all elements of a certain type. When a <Style> resource is declared without an x:Key value, the x:Key value assumes 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 style is applied only to the ToggleButton controls.

BasedOn Styles

Starting with Silverlight 3, it is possible to build a new style based on an existing style. You can do this using the BasedOn property. This reduces the duplication of code and makes it easier to manage resources. Each style supports only one BasedOn style. For more information, see the BasedOn property.

Examples

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

Implicit Styles

The following 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 implicitly to 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>

BasedOn Styles

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

Data Bound Style Values

The following Silverlight 5 example creates an implicit TextBlock style that assigns a binding markup expression to a Setter.Value property. The binding retrieves its value from a property of the current DataContext, which in this case is a simple UserSettings object. In this way, the TextBlock in the example is automatically displayed with the user's preferred FontSize setting. A TextBox bound to the same source enables users to modify the setting and see the change applied immediately.

<UserControl x:Class="SL5DataBindingFeatures.StyleTestPage"
  xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml">

  <StackPanel x:Name="LayoutRoot">

    <StackPanel.Resources>
      <Style TargetType="TextBlock">
        <Setter Property="FontSize" Value="{Binding FontSize}"/>
      </Style>
    </StackPanel.Resources>

    <TextBlock Text="FontSize"/>
    <TextBox Text="{Binding FontSize, Mode=TwoWay}"
      TextChanged="TextBox_TextChanged"/>

  </StackPanel>

</UserControl>
Imports System.ComponentModel

Partial Public Class StyleTestPage
    Inherits UserControl

    Public Sub New()
        InitializeComponent()
        DataContext = New UserSettings() With {.FontSize = 35}
    End Sub

    Private Sub TextBox_TextChanged(sender As System.Object,
                                    e As TextChangedEventArgs)
        ' Update the data source whenever the text box value changes.
        CType(sender, TextBox) _
            .GetBindingExpression(TextBox.TextProperty).UpdateSource()
    End Sub
End Class

Public Class UserSettings
    Implements INotifyPropertyChanged

    Private _fontSize As Double
    Public Property FontSize As Double
        Get
            Return _fontSize
        End Get
        Set(value As Double)
            _fontSize = value
            RaiseEvent PropertyChanged(
                Me, New PropertyChangedEventArgs("FontSize"))
        End Set
    End Property

    Public Event PropertyChanged As PropertyChangedEventHandler _
        Implements INotifyPropertyChanged.PropertyChanged

End Class
using System;
using System.ComponentModel;
using System.Windows.Controls;

public partial class StyleTestPage : UserControl
{
    public StyleTestPage()
    {
        InitializeComponent();
        DataContext = new UserSettings() { FontSize = 35 };
    }

    private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
    {
        // Update the data source whenever the text box value changes.
        (sender as TextBox)
            .GetBindingExpression(TextBox.TextProperty).UpdateSource();
    }
}

public class UserSettings : INotifyPropertyChanged
{
    private Double _fontSize;
    public Double FontSize 
    {
        get { return _fontSize; }
        set 
        {
            _fontSize = value;
            PropertyChanged(this, new PropertyChangedEventArgs("FontSize"));   
        }
    }
    // Initialize to an empty delegate so that PropertyChanged is never null.
    public event PropertyChangedEventHandler PropertyChanged = delegate { };
}

Version Information

Silverlight

Supported in: 5, 4, 3

Silverlight for Windows Phone

Supported in: Windows Phone OS 7.1, Windows Phone OS 7.0

Platforms

For a list of the operating systems and browsers that are supported by Silverlight, see Supported Operating Systems and Browsers.

Thread Safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

See Also

Reference

Other Resources