Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
like image 755
Vishal Avatar asked Mar 21 '23 07:03

Vishal


1 Answers

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>
like image 134
Heena Avatar answered Mar 22 '23 21:03

Heena