ViewBox
不允许您保持恒定的字体大小,这不是它的工作方式。您需要将文本放在视图框之外才能发生这种情况:
<Grid>
<Viewbox Stretch="Uniform">
<Canvas Width="100" Height="100">
<Ellipse Width="100" Height="100" Stroke="Black"/>
</Canvas>
</Viewbox>
<TextBlock TextAlignment="Center" FontSize="12">Top Center</TextBlock>
</Grid>
请注意,我从 中删除了 Width 属性TextBlock
,我只是让它拉伸到网格的宽度,让文本对齐来处理居中。
或者,您可以发挥创意并将FontSize
属性绑定到ActualWidth
的ViewBox
并使其适当缩放,例如:
转换器:
class ViewBoxConstantFontSizeConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (!(value is double)) return null;
double d = (double)value;
return 100 / d * 12;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotSupportedException();
}
}
用法:
<Window.Resources>
...
<local:ViewBoxConstantFontSizeConverter x:Key="conv"/>
</Window.Resources>
...
<Viewbox Name="vb" Stretch="Uniform">
<Canvas Width="100" Height="100">
<Ellipse Width="100" Height="100" Stroke="Black"/>
<TextBlock Width="100" TextAlignment="Center"
FontSize="{Binding ElementName=vb,
Path=ActualWidth,
Converter={StaticResource conv}}">
Top Center
</TextBlock>
</Canvas>
</Viewbox>