给定具有多个运行的TextBlock,如何指定相对FontSize?例如,如果TextBlock有FontSize 10,我希望其中一个运行为15.但是如果FontSize变为20,我希望Run变为30。
答案 0 :(得分:1)
您没有说这是用于WPF还是其他XAML框架。此示例适用于WPF。
这通常使用绑定和值转换器完成。
ValueConverter代码
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; }
}
在XAML资源中实例化Converter并设置Ratio属性。
<强> XAML 强>
<Window.Resources>
<local:FontSizeConverter x:Key='FontSizeConverter'
Ratio='1.5' />
</Window.Resources>
然后使用相对绑定来获取父TextBlock FontSize。将值父值传递给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>
如果要将绑定应用于TextBlock中的所有运行,可以为每次运行重复此绑定或创建使用绑定的样式。
<强> XAML 强>
<Style TargetType='Run'>
<Setter Property='FontSize'
Value='{Binding FontSize, Converter={StaticResource FontSizeConverter}, RelativeSource={RelativeSource FindAncestor, AncestorType=TextBlock}}' />
</Style>
完整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>