我有一个 Viewbox
数量为TextBlock
由 ViewBox
完美缩放和定位的 s .像这样的东西:
<Viewbox Stretch="Uniform">
<Canvas Width="100" Height="100">
<Ellipse Width="100" Height="100" Stroke="Black"/>
<TextBlock Width="100" TextAlignment="Center" FontSize="12">Top Center</TextBlock>
</Canvas>
</Viewbox>
如果用户调整
Viewbox
它的内容被完美地缩放以匹配。但是我想保留 FontSize
为 12,无论 Viewbox
的实际大小如何.我怎样才能做到这一点?我可以在 XAML 中执行此操作而不附加到
Resize
事件?
最佳答案
ViewBox
不允许您保持恒定的字体大小,这不是它的工作方式。您需要将文本放在 View 框之外才能做到这一点:
<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>
请注意,我从
TextBlock
中删除了 Width 属性。 ,我只是让它拉伸(stretch)网格的宽度,让文本对齐来处理居中。或者,您可以发挥创意并绑定(bind)
FontSize
ActualWidth
的属性(property)的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>
关于wpf - 如何在 WPF Viewbox 中保持恒定的 FontSize?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2013854/