繁体   English   中英

如何在WPF Viewbox中保留常量FontSize?

[英]How do I keep a constant FontSize in WPF Viewbox?

我有一个带有许多TextBlockViewbox ,它们由ViewBox完美缩放和定位。 像这样的东西:

<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。

我怎样才能做到这一点? 我可以在XAML中执行此操作而不附加到Resize事件吗?

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>

请注意,我从TextBlock删除了Width属性,我只是让它拉伸网格的宽度,让文本对齐处理居中。

或者,您可以获得创意并将FontSize属性绑定到ViewBoxActualWidth并使其适当缩放,例如:

转换器:

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>

这也许是一个简单的解决方案。

<Viewbox StretchDirection="DownOnly" >
     <Label Content="Enable" FontSize="10" FontStretch="Normal" />
</Viewbox>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM