Search code examples
wpfxamlwpf-style

Can I apply a WPF style to an element only in a certain layout?


I have a TextBlock style like this:

<Style TargetType="TextBlock" x:Key="FormLabel">
    <Setter Property="Height" Value="20" />
    <Setter Property="Margin" Value="10" />
    <Setter Property="TextAlignment" Value="Right" />
    <Setter Property="VerticalAlignment" Value="Center" />
</Style>

I use it in Grid based forms, e.g:

<TextBlock Text="Code" Grid.Row="1" Grid.Column="0" Style="{StaticResource FormLabel}" />

Now instead of repeating the style name on every TextBlock in the grid, I would prefer to e.g. have a Grid style like:

<Style TargetType="Grid" x:Key="FormGrid">
    <Setter Property="Width" Value="400" />
    ...
</Style>

Then I would, if possible, like to modify my TextBlock style to only apply to that element when it is a child element of a Grid with style FormGrid.

Is this possible, and if so, how can I achieve it?


Solution

  • This is indeed possible by using an implicit style within another style as a resource. Take this example:

    ...
    <Window.Resources>
        <Style x:Key="FormGrid" TargetType="Grid">
            <Style.Resources>
                <Style TargetType="TextBlock">
                    <Setter Property="Height" Value="20" />
                    <Setter Property="Margin" Value="10" />
                    <Setter Property="TextAlignment" Value="Right" />
                    <Setter Property="VerticalAlignment" Value="Center" />
                </Style>
            </Style.Resources>
            <Setter Property="Width" Value="400" />
        </Style>
    </Window.Resources>
    <StackPanel>
        <Grid Style="{StaticResource FormGrid}">
            <TextBlock Text="This text block is styled with FormGrid TextBlock implicit style."/>
        </Grid>        
        <TextBlock Text="This text block uses the default style."/>
    </StackPanel>
    ...