代码之家  ›  专栏  ›  技术社区  ›  Hallgrim

如何在WPF视图框中保持恒定的字体大小?

  •  7
  • Hallgrim  · 技术社区  · 15 年前

    我有一个 Viewbox 有很多 TextBlock 是由 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>
    

    如果用户调整 视窗 它的内容完全按比例缩放以匹配。但是我想保留 FontSize 到12,无论 视窗 .

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

    2 回复  |  直到 7 年前
        1
  •  10
  •   svick Raja Nadar    12 年前

    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 我只是让它拉伸网格的宽度,让文本对齐处理居中。

    或者,你可以发挥创造力,把 FontSize 属性到 ActualWidth 视窗 并使其适当缩放,例如:

    转换器:

    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>
    
        2
  •  6
  •   Pitka    10 年前

    这可能也是一个简单的解决办法。

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