将样式应用于所有作为StackPanel子元素的TextBlock

5
假设我有一个如下所示的布局:
<Grid>

    <TextBlock........ />
    <StackPanel>
        <TextBlock ...../>
        <!--Other Elements-->
    </StackPanel>

    <TextBlock........ />
    <StackPanel>
        <TextBlock ...../>
        <!--Other Elements-->
    </StackPanel>

    <TextBlock........ />
    <StackPanel>
        <TextBlock ...../>
        <!--Other Elements-->
    </StackPanel>

</Grid>

现在我想将以下样式应用于上述布局中 StackPanel 的所有文本块的子元素。
<Style TargetType={x:Type TextBlock}>
    <Setter Property="FontSize" Value="20" />
<Style>
1个回答

8

第一种方法:

示例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>

例子2:如果你想要在特定的网格中使用文本块堆栈面板

<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>

第二种方法:为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>

例子2在你的回答中帮助我解决了我的问题。谢谢Heena提供如此好的答案。 - Vishal

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接