Style 类

定义

包含可在类型实例之间共享的属性资源库。 Style通常在资源集合中声明 ,以便可以共享并用于应用控件模板和其他样式。

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

示例

此示例创建两种样式:一个用于 TextBlock ,一个用于 TextBox。 每个样式都应用于控件的两个实例,以便为每个 TextBlockTextBox创建统一的外观。 该示例通过将 引用Style{StaticResource} 标记扩展来设置每个控件的 FrameworkElement.Style 属性。 该示例还演示如何从资源字典中检索样式,并将其应用于代码中的控件。

每个样式都有多个 Setter 部分。 在此 XAML 中,不 Style.Setters 显示 XAML 属性元素。 这是 XAML 中此属性的典型用法。 该值 Style.Setters 是隐式的,因为 Setters 是 Style 的 XAML 内容属性。 有关 XAML 语法以及 XAML 内容语法如何使暗示和省略某些 XAML 元素的详细信息,请参阅 XAML 语法指南

请注意,在 TextBox 的样式中, Margin 属性设置为 4,这意味着 TextBox 所有边距为 4。 为了补偿第二个 TextBlock 的长度,该长度比第一个 TextBlock 短,因为 姓氏 占用的空间小于 名字,第二个属性的值“6,4,4,4”分配给 Margin 第二 TextBox个属性。 这会导致第二 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第一个样式元素的 设置为 TextBoxTargetType第二个样式元素的 设置为 Button。 然后,这些应用作为控件和控件的TextBoxButton隐式样式。

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

此示例创建一个Style基于Style命名 BaseStyle 的命名 InheritedStyleInheritedStyleBaseStyle 继承 Background 的值Yellow,并添加 ForegroundRed

<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一个属性和一个Property是应用样式的元素的属性的名称。 Value是应用于 属性的值。

若要应用 , Style目标对象必须是 DependencyObject。 每个 Setter 引用为 属性值的属性 必须是依赖属性。

创建 Style时,必须设置 TargetType 属性。 否则会引发异常。

如果为 中 和 元素中的 Style 同一属性设置值,则直接在 元素上设置的值优先。 有关详细信息,请参阅 依赖属性概述,特别是“依赖属性值优先级”部分。

样式 定义为 XAML 资源

Style在 XAML 中,几乎总是将 定义为 ResourceDictionary 中的资源

  • 对于仅由同一 Style XAML 页中定义的其他 UI 项使用的 ,如果根元素是 Page) Page.Resources,则通常会在 FrameworkElement.Resources 集合中定义 Style (。
  • Style对于应用中多个页面使用的 ,通常在 Application.Resources 集合中定义 Style。 或者,你可能具有作为 MergedDictionaries 值包含在中的应用Application.Resources的单独 XAML 文件。
  • 大多数 UI 元素具有由Windows 运行时定义的默认样式。 默认样式的副本可以在名为 generic.xaml 的设计帮助程序 XAML 文件中查看,该文件在技术上不是应用的资源文件,尽管其结构类似于一个。 编辑由工具启用的样式副本时,可以将此文件的离散部分复制到应用的 XAML 中,作为起点,但创建此类副本后,需要将其包含在其中一个 Resources 集合中或通过 MergedDictionaries 间接访问。 在所有这些情况下,将替代默认值的已修改 XAML 作为应用的一部分包含在内。

StyleResourceDictionary 中定义的元素不需要具有 x:Key 属性x:Name 属性,这通常是 XAML 资源的要求。 以这种方式定义的 , Style 使用其 TargetType 属性值作为隐式键,称为隐式样式。

有关如何使用 XAML 资源字典的详细信息,请参阅 ResourceDictionary 和 XAML 资源引用

样式和模板

可以使用 中的 StyleSetter 将值应用于任何依赖属性。 但是,Setter它是控件派生类的 Template 属性,它构成了典型 Style中的大多数 XAML 标记。 具有 Property="Template"Setter几乎总是指定为包含 ControlTemplate 对象元素的属性元素。

Style使用 定义控件模板时,元素的 StyleTargetType 及其 Control.Template setter 的 ControlTemplate 元素的 TargetType 应始终使用相同的值。

模板资源库为应用该模板的控件实例定义基本模板 UI 定义。 它还包含控件的视觉状态以及其他基于状态的 UI 定义,例如默认主题切换。 对于复杂控件(如 ListBox),默认模板 Style 和中的 ControlTemplate 可以包含数百行 XAML。 有关 在控件模板化方案中的角色 Style 的详细信息,请参阅 XAML 控件模板

控件的模板通常包括视觉状态,这些状态更改控件的外观以响应逻辑状态。 例如,通过应用其模板中的新视觉状态来按下按钮时, 按钮 可以具有不同的视觉外观,并且所有外观更改都可以来自 XAML 而不是代码。 有关视觉状态的工作原理以及如何修改它们或定义自定义控件的状态的详细信息,请参阅 XAML 控件模板

样式和运行时行为

可以更改在运行时由 Style 设置的各个属性的值,新值将覆盖 Setters 值。 例如,可以在运行时设置 Template 属性,即使此属性已按样式设置。

可以在运行时调整 的属性 Style ,但前提是该样式尚未应用于任何内容,并且仅作为未隐式使用的资源存在。 例如,您可以向 Setters 中的集合添加 setters,该样式存在于 资源 中具有 x:Key 属性 ,但在 XAML 中的其他位置没有引用该样式的 {StaticResource} 标记扩展 值。 但是,只要加载的对象引用 Style 并将其用于值, Style 就应将 视为密封。 可以通过检查 的 IsSealed 属性的值来 Style检测密封状态。 true如果是 ,则样式将被密封,并且你不能修改它的任何属性或内部的 Setter 子值。 当引用 的对象引发其 Loaded 事件时Style,还可以检测到样式投入使用和密封的时间点。

BasedOn 样式

可以基于应用定义的现有样式或Windows 运行时控件的默认样式来生成新样式。 可以使用 BasedOn 属性执行此操作。 这样可以减少 XAML 中的重复,并更轻松地管理资源。 每个样式仅支持一种 BasedOn 样式。 有关详细信息,请参阅 BasedOn样式控件

隐式样式

可以定义样式,以便 Style 由同一 TargetType 的所有对象隐式使用,而无需此类对象的每个实例专门引用 Style 作为 FrameworkElement.Style 值。 <Style>如果在没有 x:Key 属性ResourceDictionary 中声明资源,x:Key 值将使用 属性的值TargetType。 如果隐式设置样式,则样式将仅应用于与 完全匹配 TargetType 的类型,而不应用于从值派生的 TargetType 元素。 例如,如果为应用程序中的所有 ToggleButton 控件隐式创建样式,并且应用程序具有 ToggleButtonCheckBox 控件 (CheckBox 派生自 ToggleButton) ,则“ToggleButton”隐式样式仅应用于 ToggleButton 控件。

有关 XAML 语法的说明

Setters 是 的 StyleXAML 内容属性,因此可以使用隐式集合语法,例如 <Style><Setter .../><Setter .../></Style>

Style在代码中使用 类 (例如调用构造函数并逐个生成 Setter 值) 是非常罕见的。 样式用于模板,模板应在 XAML 加载时可用,因此在代码中创建的任何 Style 内容通常都为时已晚,无法应用于 UI 中的控件。

构造函数

Style()

初始化 Style 类的新实例,其中没有初始 TargetType 和空 的 Setters 集合。

Style(TypeName)

使用指定的初始 TargetType 和空的 Setters 集合初始化 Style 类的新实例。

属性

BasedOn

获取或设置一个作为当前样式的基准的已定义样式。

Dispatcher

始终在Windows 应用 SDK应用中返回 null 。 请改用 DispatcherQueue

(继承自 DependencyObject)
DispatcherQueue

DispatcherQueue获取与此对象关联的 。 表示 DispatcherQueue 一个可以在 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)

适用于

另请参阅