Export (0) Print
Expand All

Style.TargetType Property

Gets or sets the type for which this style is intended.

Namespace:  System.Windows
Assembly:  PresentationFramework (in PresentationFramework.dll)
XMLNS for XAML: http://schemas.microsoft.com/winfx/2006/xaml/presentation, http://schemas.microsoft.com/netfx/2007/xaml/presentation

[AmbientAttribute]
[LocalizabilityAttribute(LocalizationCategory.NeverLocalize)]
public Type TargetType { get; set; }
<object TargetType="{x:Type typeName}"/>
-or-
<object TargetType="typeName"/>

XAML Values

{x:Type ...}

An x:Type Markup Extension markup extension usage.

typeName

The type name of the class.

Property Value

Type: System.Type
The target type for this style.

You can set a style on any element that derives from FrameworkElement or FrameworkContentElement. Therefore, your target type can be any of those elements. 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.

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.

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>

Setting the TargetType property to the TextBlock type without setting an x:Key implicitly sets the x:Key to {x:Type 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. Instead, you need to apply the style to the TextBlock elements explicitly.

Many WPF controls consist of a combination of other WPF controls, so creating a style that applies to all controls of a type can have broad impact. 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.

.NET Framework

Supported in: 4.6, 4.5, 4, 3.5, 3.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1
Show:
© 2015 Microsoft