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 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" FontSize="10" Height="Auto" BorderThickness="3,0,0,0" Content="{Binding Path=Name}" Foreground="{DynamicResource RecordIndexTabForeground}" />
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
How can I do this?
-
You might be able to use a ValueConverter on the FontSize property.. but I'm not 100% sure if they work inside a ControlTemplate.. I seem to remember Silverlight having issues with it, but I can't remember if it worked in WPF.
-
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>
-
If you want to set the FontSize in the code behind, you should remove FontSize from the ControlTemplate, then set it for the ListBoxItem in the code-behind. If you want to set the same size for all the ListBoxItems just set the FontSize of the ListBox in the code-behind.
0 comments:
Post a Comment