代码之家  ›  专栏  ›  技术社区  ›  ScottG

如何更改ControlTemplate中标签的字体大小

  •  2
  • ScottG  · 技术社区  · 16 年前

    在我的WPF列表框中,我有一个ListBoxItem的ControlTemplate样式。在ControlTemplate中,我定义了一个标签。根据一些细节,我需要更改标签的字体大小。因此,根据我的代码,我需要确定字体应该是什么,然后我需要设置它。

    这是我使用ControlTemplate的风格(我去掉了一些不相关的控件)

    <Style x:Key="RecordTabList" TargetType="{x:Type ListBoxItem}">
                <Setter Property="Background" Value="{DynamicResource RecordIndexTabBackcolor}" />
                <Setter Property="Template">
                    <Setter.Value>
                        <ControlTemplate>        
                                <Label
                                    x:Name="myLabel" Grid.Column="0" Grid.ColumnSpan="1" Grid.Row="0" Grid.RowSpan="1" Margin="3,-2,0,-2" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Foreground="{DynamicResource RecordIndexTabForeground}" 
                                    FontSize="10" Height="Auto" BorderThickness="3,0,0,0"
                                    Content="{Binding Path=Name}" />
                            </Grid>
                        </ControlTemplate>
                    </Setter.Value>
                </Setter>
    

    我该怎么做?

    3 回复  |  直到 13 年前
        1
  •  5
  •   Mark Carpenter    16 年前

    如果我没理解错的话,您可能可以做类似于以下的事情,只需更改ListBoxItem本身的FontSize属性;它将自动反映在您的标签上。把这个复制到VS中,看看它的实际效果!

    <Window.Resources>
        <Style TargetType="ListBoxItem">
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="ListBoxItem">
                        <Label Content="{TemplateBinding Content}" FontSize="{TemplateBinding FontSize}"/>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </Window.Resources>
    <Grid>
        <ListBox Margin="12">
            <ListBoxItem Content="Test 1" FontSize="14"/>
            <ListBoxItem Content="Test 2" FontSize="18"/>
            <ListBoxItem Content="Test 3" FontSize="22"/>
        </ListBox>
    </Grid>
    
        2
  •  0
  •   Steven Robbins    16 年前

    您或许可以使用 ValueConverter 在FontSize属性上。。但我不能100%确定它们是否在ControlTemplate中工作。。我似乎记得Silverlight有问题,但我不记得它在WPF中是否有效。

        3
  •  0
  •   timothymcgrath    16 年前

    如果你想在代码后面设置FontSize,你应该从ControlTemplate中删除FontSize,然后在代码后面为ListBoxItem设置它。如果要为所有ListBoxItems设置相同的大小,只需在后面的代码中设置列表框的字体大小。

    推荐文章