【问题标题】:How do I keep a constant FontSize in WPF Viewbox?如何在 WPF Viewbox 中保持恒定的 FontSize?
【发布时间】:2011-01-02 02:24:23
【问题描述】:

我有一个Viewbox 和许多TextBlocks,它们由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 事件吗?

【问题讨论】:

    标签: wpf xaml resize font-size viewbox


    【解决方案1】:

    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 来处理文本的位置,但不是 FontSize。
    • 添加了我的答案的替代方案,试试吧。这有点过度创意,但它可能会起作用:)
    • 令人印象深刻!那行得通,但我希望有一些更简单的东西。
    • 您还可以制定一个更通用的解决方案,即视图框内的视图框,内部视图框尺寸绑定到外部视图框尺寸,每个尺寸上的缩放比例相似。
    • 如果你不希望它变大,也可以使用 StretchDirection="DownOnly"。
    【解决方案2】:

    这可能也很容易解决。

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

    【讨论】:

      猜你喜欢
      • 2017-08-01
      • 2018-11-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-11
      • 2018-02-04
      • 2014-10-15
      相关资源
      最近更新 更多