Style.TargetType 属性

定义

获取或设置此样式所针对的类型。Gets or sets the type for which this style is intended.

public:
 property Type ^ TargetType { Type ^ get(); void set(Type ^ value); };
[System.Windows.Localizability(System.Windows.LocalizationCategory.NeverLocalize)]
[System.Windows.Markup.Ambient]
public Type TargetType { get; set; }
member this.TargetType : Type with get, set
Public Property TargetType As Type

属性值

此样式的目标类型。The target type for this style.

属性

示例

下面的示例定义了将应用于TextBlock元素的所有实例的样式。The following example defines a style that will be applied to all instances of the TextBlock element.

<Style TargetType="{x:Type TextBlock}">
  <Setter Property="FontFamily" Value="Segoe Black" />
  <Setter Property="HorizontalAlignment" Value="Center" />
  <Setter Property="FontSize" Value="12pt" />
  <Setter Property="Foreground" Value="#777777" />
</Style>

x:Key {x:Type TextBlock} x:Key如果将TextBlock属性设置为类型, 而不将设置设置为, 则将隐式设置为。 TargetTypeSetting the TargetType property to the TextBlock type without setting an x:Key implicitly sets the x:Key to {x:Type TextBlock}. 这也意味着, Style如果给x:Key出的{x:Type TextBlock}值不是, Style则不会自动应用于所有TextBlock元素。This also means that if you give the above Style an x:Key value of anything other than {x:Type TextBlock}, the Style would not be applied to all TextBlock elements automatically. 相反, 需要显式将样式应用到TextBlock元素。Instead, you need to apply the style to the TextBlock elements explicitly.

许多WPFWPF控件包含其他WPFWPF控件的组合, 因此, 创建适用于某个类型的所有控件的样式可能会产生很大的影响。Many WPFWPF controls consist of a combination of other WPFWPF controls, so creating a style that applies to all controls of a type can have broad impact. 例如, 如果您创建一个样式, 该样式面向TextBox Canvas中的控件, 则该样式将应用于TextBox画布中的所有TextBox控件, 即使是另一个控件ComboBox(例如) 的一部分。For instance, if you create a style that targets the TextBox controls in a Canvas, the style is applied to all TextBox controls in the canvas, even if the TextBox is part of another control, such as a ComboBox.

注解

可以对从FrameworkElementFrameworkContentElement派生的任何元素设置样式。You can set a style on any element that derives from FrameworkElement or FrameworkContentElement. 因此, 目标类型可以是这些元素中的任何一个。Therefore, your target type can be any of those elements. 但是, 如果您创建一个具有TargetType属性的样式, 并基于另一个同时TargetType定义属性的样式, 则该派生样式的目标类型必须与基样式的目标类型相同或派生。However, if you create a style with a TargetType property and base it on another style that also defines a TargetType property, the target type of the derived style must be the same as or be derived from the target type of the base style.

如果未指定TargetType, 则必须x:KeyStyle指定, 还应使用类名称限定样式中的属性。If you do not specify a TargetType, then you must specify an x:Key for your Style and also qualify the properties in your style with a class name.

XAML 属性用法XAML Attribute Usage

<object  TargetType="{x:Type typeName}"/>  
-or-  
<object  TargetType="typeName"/>  

XAML 值XAML Values

{x:Type ...}
X:Type 标记扩展标记扩展用法。An x:Type Markup Extension markup extension usage.

typeNametypeName
类的类型名称。The type name of the class.

适用于

另请参阅