given a TextBlock with multiple Runs, how can I specify a relative FontSize? For example, if the TextBlock has FontSize 10, I would like one of the Runs to be 15. But if the FontSize becomes 20, I would like the Run to become 30.
Asked
Active
Viewed 2,529 times
1 Answers
4
You didn't say whether this was for WPF or other XAML framework. This sample works in WPF.
This is typically done with binding and a Value Converter.
ValueConverter Code
class FontSizeConverter : IValueConverter {
public object Convert(object value, Type targetType, object parameter,
System.Globalization.CultureInfo culture) {
// add input parameter testing as needed.
var originalFontSize = (double)value;
double alteredFontSize = originalFontSize * Ratio; ;
return alteredFontSize;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) {
throw new NotImplementedException();
}
// Create a ratio property
// allows the converter to be used for different font ratios
public double Ratio { get; set; }
}
Instantiate the Converter in the XAML resources and set the Ratio property.
XAML
<Window.Resources>
<local:FontSizeConverter x:Key='FontSizeConverter'
Ratio='1.5' />
</Window.Resources>
Then use a relative binding to get the parent TextBlock FontSize. Pass the value parent value to a ValueConverter.
XAML
<TextBlock FontSize='20'>
<Run Text='The first bit.'
FontSize='{Binding FontSize, Converter={StaticResource FontSizeConverter}, RelativeSource={RelativeSource FindAncestor, AncestorType=TextBlock}}' />
<Run Text='The second bit' />
<Run Text='The third bit' />
</TextBlock>
If you want to apply the binding to all the Runs in the TextBlock you can repeat this binding for each Run or create a Style which uses the binding.
XAML
<Style TargetType='Run'>
<Setter Property='FontSize'
Value='{Binding FontSize, Converter={StaticResource FontSizeConverter}, RelativeSource={RelativeSource FindAncestor, AncestorType=TextBlock}}' />
</Style>
Full XAML
<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local='clr-namespace:SO_Questions'
x:Class="SO_Questions.TextRunWindow"
Title="TextRunWindow"
Height="600"
Width="600">
<Window.Resources>
<local:FontSizeConverter x:Key='FontSizeConverter'
Ratio='2.5' />
<Style TargetType='Run'>
<Setter Property='FontSize'
Value='{Binding FontSize, Converter={StaticResource FontSizeConverter}, RelativeSource={RelativeSource FindAncestor, AncestorType=TextBlock}}' />
</Style>
</Window.Resources>
<Grid>
<TextBlock FontSize='20'>
<Run Text='The first bit.'
FontSize='{Binding FontSize, Converter={StaticResource FontSizeConverter}, RelativeSource={RelativeSource FindAncestor, AncestorType=TextBlock}}' /><Run Text=' ' />
<Run Text='The second bit' />
<Run Text='The third bit' />
</TextBlock>
</Grid>
</Window>

Walt Ritscher
- 6,977
- 1
- 28
- 35