I'll jump to the chase: Is there any way to tell the WPF TextBlock
to measure itself such that its size doesn't change when its FontWeight
changes?
I have a TextBlock
that changes font weights dynamically based on a style. The TextBlock
is inside a RadioButton
so it is Bold when checked, Normal otherwise:
<Style x:Key="BoldWhenChecked" TargetType="RadioButton">
<Style.Triggers>
<Trigger Property="IsChecked" Value="True">
<Setter Property="TextElement.FontWeight" Value="Bold" />
</Trigger>
</Style.Triggers>
</Style
and here are the radio buttons themselves:
<StackPanel Orientation="Horizontal">
<RadioButton Style="{StaticResource BoldWhenChecked}">
<TextBlock Text="Item 1" />
</RadioButton>
<RadioButton Style="{StaticResource BoldWhenChecked}">
<TextBlock Text="Item 2" />
</RadioButton>
<RadioButton Style="{StaticResource BoldWhenChecked}">
<TextBlock Text="Item 3" />
</RadioButton>
etc...
</StackPanel>
Unfortunately, since I am not using a fixed-width font the width of the TextBlock
changes when the font weight changes, and the entire panel of radio buttons shifts accordingly, which is visually jarring.
I created a work-around for this by adding a hidden TextBlock
in the content of the RadioButton
with its FontStyle
explicitly set to Bold
:
<RadioButton Style="{StaticResource BoldWhenChecked}">
<Grid>
<TextBlock Text="Item 1" />
<TextBlock Text="Item 1" FontStyle="Bold" Visibility="Hidden" />
</Grid>
</RadioButton>
That way when the RadioButton is selected and the visible TextBlock
is made bold, the width does not change because the hidden TextBlock
has already sized the grid appropriately.