1

I have a question regarding styles in xaml wpf.

I have a Default style which should apply for all Objects. But for some of them I want to set a second style overriding a few attributes.

Now if I give my second style a x:key="style2" and set this as style, my first Default style is not applied, but the Default WPF style is. I can not/want not Change anything at my first Default style

How can I fix this behaivor?

1 Answer 1

6

To ensure that your default style is still applied, you add

BasedOn={StaticResource ResourceKey={x:Type ControlType}} 

Where ControlType is the type of object the default style was applied to.

Here's an example:

enter image description here

<Window x:Class="StyleOverrides.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="350" Width="525"> <Window.Resources> <Style TargetType="{x:Type TextBlock}"> <Setter Property="FontFamily" Value="Comic Sans MS" /> </Style> <Style x:Key="Specialization" TargetType="{x:Type TextBlock}" BasedOn="{StaticResource ResourceKey={x:Type TextBlock}}" > <Setter Property="FontStyle" Value="Italic" /> <Setter Property="Foreground" Value="Blue" /> </Style> </Window.Resources> <Grid> <Grid.RowDefinitions> <RowDefinition Height="*" /> <RowDefinition Height="*" /> </Grid.RowDefinitions> <Viewbox Grid.Row="0" > <TextBlock>This uses the default style</TextBlock></Viewbox> <Viewbox Grid.Row="1"> <TextBlock Style="{StaticResource Specialization}"> This is the specialization </TextBlock> </Viewbox> </Grid> </Window> 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.