【问题标题】:Is there a more elegant way to auto resize label font size?有没有更优雅的方法来自动调整标签字体大小?
【发布时间】:2019-02-15 15:42:45
【问题描述】:

我有一个带有多个标签和其他控件的 WPF UI。我希望标签内文本的大小与窗口大小一起缩放。

将标签放在 Viewbox 中可以满足我的要求,但我觉得将每个标签放在它自己的 Viewbox 中有点“不美观”。

<Viewbox Grid.Row="1">
    <Label>PA-Nummer</Label>
</Viewbox>

是否有一种仅 Xaml(使用 MVVM 模式)的方法来更有效地执行此操作?

【问题讨论】:

  • 您可以将窗口的全部内容放在一个视图框中。顺便说一句,这似乎有点不寻常的要求。
  • @Andy 就像一个魅力。谢谢。为什么文本随窗口缩放是一个不寻常的要求?
  • 缩放此页面时会发生这种情况吗?或word或excel....或几乎任何东西?图形应用程序会发生这种情况,而商业应用程序则不然。
  • 嗯,它是一个生产工人的应用程序,所有元素都应该随时可见,无需滚动,元素应该尽可能大。我明白你的意思,在日常桌面应用程序中这可能确实不常见,但在工业和生产前端,我不会第一次看到这种行为。

标签: c# wpf resize


【解决方案1】:

如果您想要缩放整个内容(不仅仅是文本),您可以执行以下操作。假设您对 Window(名为 MyWindow)的顶级控制是 Grid,这里是 XAML:

<Window.Resources>
    <c:WindowWidthToScaleConverter x:Key="WindowWidthToScaleConverter" />
</Window.Resources>

<Grid>
    <Grid.LayoutTransform>
        <ScaleTransform
            ScaleX="{Binding ActualWidth, ElementName=MyWindow, Converter={StaticResource WindowWidthToScaleConverter}}"
            ScaleY="{Binding ActualWidth, ElementName=MyWindow, Converter={StaticResource WindowWidthToScaleConverter}}"
            />
    </Grid.LayoutTransform>
    <!-- Contents -->
</Grid>

这是转换器,假设宽度为 640 是正常 (1:1) 比例:

public class WindowWidthToScaleConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value is double width)
            return width / 640.0;
        return 1.0;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return null;
    }
}

更新:但是,上述解决方案只会使字体大小(和控件)看起来变大,但实际上不会改变字体大小。如果你只是想改变Label控件的字体大小,你可以在XAML中进行如下操作:

<Window.Resources>
    <c:WindowWidthToFontSizeConverter x:Key="WindowWidthToFontSizeConverter" />
    <Style TargetType="Label">
        <Setter
            Property="FontSize"
            Value="{Binding ActualWidth, ElementName=MyWindow,
                Converter={StaticResource WindowWidthToFontSizeConverter}}"
            />
    </Style>
</Window.Resources>

<StackPanel>
    <Label Content="Name:" />
    <TextBox />
</StackPanel>

转换器假定 640 的宽度对应于 12.0 的字体大小并相应地缩放:

public class WindowWidthToFontSizeConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value is double width)
            return 12.0 * width / 640.0;
        return 12.0;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return null;
    }
}

您可以添加类似的Style 资源来缩放其他控件的字体大小。但是即使控件派生自Control 类,您也不能以这种方式为所有控件定义Style。但是,有一个解决方法可以解释here

【讨论】:

  • 我试过了,但是标签文本的字体大小保持不变。
  • 是的,字体大小的外观会缩放,但实际的FontSize 保持不变。我已使用可扩展 FontSize 的解决方案更新了我的答案。
  • 抱歉,我的评论措辞不当。我的意思是,它在屏幕上也不会显得更大。然而,安迪在我的 OP 的 cmets 中提出的解决方案成功了。不过还是谢谢你。
猜你喜欢
  • 2011-02-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-11-13
  • 1970-01-01
  • 2011-04-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多