如何在WPF Viewbox中保持恒定的FontSize? [英] How do I keep a constant FontSize in WPF Viewbox?

查看:536
本文介绍了如何在WPF Viewbox中保持恒定的FontSize?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Viewbox,其中有许多TextBlock,它们由ViewBox完美缩放和定位.像这样:

I have a Viewbox with a number of TextBlocks that are scaled and positioned perfectly by the ViewBox. Something like this:

<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的大小,则其内容将完美缩放以匹配.但是,无论Viewbox的实际大小如何,我都希望将FontSize保持为12.

If the user resizes the Viewbox its contents are perfectly scaled to match. However I would like to keep the FontSize to 12 regardless of the actual size of the Viewbox.

我该怎么做?我可以在XAML中执行此操作而不附加到Resize事件吗?

How can I do this? Can I do this in XAML without attaching to an Resize event?

推荐答案

ViewBox不允许您保持恒定的字体大小,这不是它的工作原理.您需要将文本放在视图框外才能实现:

ViewBox won't allow you to keep a constant font size, that's just not how it works. You need to put the text outside the view box for that to happen:

<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属性,只是让它沿网格的宽度伸展,让文本对齐方式保持居中.

Note that I removed the Width property from the TextBlock, I just let it stretch for the width of the grid, letting the text alignment take care of the centering.

或者,您可以发挥创意并将FontSize属性绑定到ViewBoxActualWidth并对其进行适当缩放,例如:

Or, you could get creative and bind the FontSize property to the ActualWidth of the ViewBox and having it scaled appropriately, for example:

转换器:

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 Viewbox中保持恒定的FontSize?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆