Search code examples
.netwpfxamltargettype

when to use {x:Type …} for Style TargetType?


What is the difference between:

<Style TargetType="{x:Type Border}">

and:

<Style TargetType="Border">

When and why do I need to use the {x:Type …} ?


Solution

  • There is no difference in effect; in both cases the TargetType property will be set to typeof(Border)

    The first version {x:Type Border} was needed in the first version of WPF because the compiler did not use the TypeConverter class to convert the string into a Type object and you needed to specify the TypeExtension class to do that for you.

    The second version was introduced, if I remember correctly, with Silverlight and quickly found its way to the WPF compiler.

    EDIT

    My assumption on the TypeConverter class was wrong; this is implemented by the FrameworkElementFactory:

    From the documentation:

    Type Properties That Support Typename-as-String

    WPF supports techniques that enable specifying the value of some properties of type Type without requiring an x:Type markup extension usage. Instead, you can specify the value as a string that names the type. Examples of this are ControlTemplate.TargetType and Style.TargetType. Support for this behavior is not provided through either type converters or markup extensions. Instead, this is a deferral behavior implemented through FrameworkElementFactory.

    Silverlight supports a similar convention. In fact, Silverlight does not currently support {x:Type} in its XAML language support, and does not accept {x:Type} usages outside of a few circumstances that are intended to support WPF-Silverlight XAML migration. Therefore, the typename-as-string behavior is built-in to all Silverlight native property evaluation where a Type is the value.