Search code examples
c#wpfxamltargettype

Setting a style's TargetType property to a generic class


Is it possible to set a style's TargetType property in XAML to a Generic Class?

public class Selector<T> : Control { }

and then in xaml

<Style x:TargetType="Selector">
<Setter Property="MyProperty" Value="Green" />
</Style>

This wont work because Selector is missing a type argument.


Solution

  • You cannot bind to an open generic type like List<T>, you can however bind to a closed generic type like List<Person> by defining a placeholder type.

    C#:

    class People : List<Person> {}
    

    XAML:

    <Style TargetType="{x:Type People}"> ... </Style>
    

    Update: You either need to specify TargetType or the x:Key property for a Style, not both.