Vishal
Vishal

Reputation: 6368

Applying a style to all the TextBlocks that are children of StackPanel

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>

Upvotes: 5

Views: 2981

Answers (1)

Heena
Heena

Reputation: 8634

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>

Upvotes: 8

Related Questions