Suppose I have a layout as below:
<Grid>
    <TextBlock........ />
    <StackPanel>
        <TextBlock ...../>
        <!--Other Elements-->
    </StackPanel>
    <TextBlock........ />
    <StackPanel>
        <TextBlock ...../>
        <!--Other Elements-->
    </StackPanel>
    <TextBlock........ />
    <StackPanel>
        <TextBlock ...../>
        <!--Other Elements-->
    </StackPanel>
</Grid>
Now I want to apply a style like below to all the textblocks that are children of StackPanel in above mentioned layout.
<Style TargetType={x:Type TextBlock}>
    <Setter Property="FontSize" Value="20" />
<Style>
First Method:
Example 1:
 <Window.Resources>
    <Style TargetType="StackPanel">
        <Style.Resources>
            <Style TargetType="TextBlock">
                <Setter Property="FontSize" Value="20" />                    
            </Style>
        </Style.Resources>
    </Style>
</Window.Resources>
 <StackPanel>
     <TextBlock/>                
 </StackPanel>           
 <StackPanel>
     <TextBlock />                
 </StackPanel>
Example 2: if you want textblock-stackpanel in particular grid
<Window.Resources>
    <Style x:Key="Textblockstyle" TargetType="Grid">
        <Style.Resources>
            <Style TargetType="StackPanel">
                <Style.Resources>
                    <Style TargetType="TextBlock">
                        <Setter Property="FontSize" Value="20" />
                        <Setter Property="Foreground" Value="Green"/>
                    </Style>
                </Style.Resources>
            </Style>
        </Style.Resources>
    </Style>
</Window.Resources>
<Grid>
    <StackPanel Height="100" VerticalAlignment="top" Width="100">
        <TextBlock Text="Another Grid" />
    </StackPanel>
    <Grid Style="{StaticResource Textblockstyle}">
        <StackPanel Height="100" HorizontalAlignment="Left" Width="100">
            <TextBlock Text="Textblock1" />
        </StackPanel>
        <StackPanel Height="100" HorizontalAlignment="Right" Width="100">
            <TextBlock Text="Textblock2"/>
        </StackPanel>
    </Grid>
</Grid>
Second Method :Give style name to every textblock in stackpanel
<Window.Resources>
    <Style x:Key="Textblockstyle" TargetType="TextBlock">
        <Setter Property="FontSize" Value="20" />
        <Setter Property="Foreground" Value="Green"/>
    </Style>
</Window.Resources>
 <StackPanel>
    <TextBlock Text="abc" Style="{StaticResource Textblockstyle}"/>
   <!--Other Elements-->
 </StackPanel>
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