Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I have one Style with multiple TargetType in WPF?

As titled, and I mean something like below:

<Style TargetType="{x:Type TextBlock}"         TargetType="{x:Type Label}"          TargetType="{x:Type Button}" > 

This is actually for the sake of using a 3rd party control, I have inherited their class. But the template doesn't apply to the SubClass because the TargetType is on the base class. So I would like to set multiple TargetTypes to make it able to apply for both.

like image 752
King Chan Avatar asked Feb 10 '12 18:02

King Chan


People also ask

Can style be inherited or extended in WPF?

WPF provides a way to inherit the style by another one. BasedOn property helps us to achieve this.

How to inherit style in WPF?

When you inherit a style from an existing style, the settings from a parent style are available in the inherited style. To inherit a style from another style, we set the BasedOn property to StaticResource Markup Extension as the style it is being inherited from.

What is a style in WPF?

Styles provide us the flexibility to set some properties of an object and reuse these specific settings across multiple objects for a consistent look. In styles, you can set only the existing properties of an object such as Height, Width, Font size, etc. Only default behavior of a control can be specified.


2 Answers

No you cannot, however I often create a style for a shared base class such as FrameworkElement, and then create my individual control styles that are BasedOn the base style

<Style TargetType="{x:Type FrameworkElement}">     <!-- Shared Setters --> </Style>  <Style TargetType="{x:Type TextBlock}" BasedOn="{StaticResource {x:Type FrameworkElement}}" /> <Style TargetType="{x:Type Label}" BasedOn="{StaticResource {x:Type FrameworkElement}}" /> <Style TargetType="{x:Type Button}" BasedOn="{StaticResource {x:Type FrameworkElement}}" /> 
like image 86
Rachel Avatar answered Sep 29 '22 15:09

Rachel


A more flexible variation of Rachel's answer is to use resourceKey for BasedOn.

So, instead of:

<Style TargetType="{x:Type FrameworkElement}">     <!-- Shared Setters --> </Style> <Style TargetType="{x:Type TextBlock}" BasedOn="{StaticResource {x:Type FrameworkElement}}" /> 


Do something like:

<Style x:Key="commonStyle" TargetType="{x:Type FrameworkElement}">     <!-- Shared Setters --> </Style> <Style TargetType="{x:Type TextBlock}" BasedOn="{StaticResource commonStyle}" /> 


This gives more options as some styles can be based on commonStyle, and some on e.g. commonStyle2, where both commonStyle and commonStyle2 have FrameworkElement as target type.

like image 27
alterfox Avatar answered Sep 29 '22 15:09

alterfox