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 TargetType
s to make it able to apply for both.
WPF provides a way to inherit the style by another one. BasedOn property helps us to achieve this.
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.
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.
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}}" />
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With