How can I change the font size of a label in my ControlTemplate

18,852

If I understand you correctly, you can probably do something similar to the following, and simply change the FontSize property on the ListBoxItem itself; it will be reflected automatically on your Label. Copy this into VS and see it in action!

<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>
Share:
18,852
ScottG
Author by

ScottG

I am a software architect in Detroit, Michigan specializing in e-commerce on the Microsoft stack (ASP.NET MVC, WPF, WCF, SQL Server, and C#). I write software that integrates with Amazon MWS and AWS, Paypal, Google, Jet, and ChannelAdvisor among others.

Updated on June 04, 2022

Comments

  • ScottG
    ScottG almost 2 years

    In my WPF ListBox, I have a style with a ControlTemplate for a ListBoxItem. Inside that ControlTemplate I have a label defined. Based on some details, I need to change the font size of the label. So from my code-behind, I need to determine what the font should be and then I need to set it.

    Here is my style with the ControlTemplate (I've stripped out some irrelevant controls)

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

    How can I do this?