C# Win Forms 应用程序标准字体抛出异常(“Height”属性)

问题描述 投票:0回答:2

我有一个 Win Form C# 应用程序,允许用户设置标签的字体。默认字体存储在该应用程序的 Properties.Settings 条目中,并使用字体对话框进行选择。

Properties.Settings

enter image description here

在我的应用程序中,我将此字体分配给标签:

Label.Font = Glob.ps.evFont; // Glob.ps is the Property.Settings for this app

由于某种原因,当我尝试显示此标签时,出现与字体的“高度”属性相关的“参数无效”异常。

enter image description here

我尝试过的字体都是非常普通的 Windows 字体(Arial、Segoe UI 等)。如果我在标签中明确创建字体,则应用程序可以正常工作:

Label.Font = new Font("Arial", 12.0F, FontStyle.Bold);

有什么想法吗?

c# winforms exception fonts
2个回答
1
投票

是否有可能正确读取设置?
创建了一个空的 winform 项目来测试通过应用程序设置设置字体,并最终得到像这样的代码后面的代码,并且工作正常。
设置断点并在应用字体后看到标签高度属性发生变化(增加)。

    namespace WinForm
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();

                // Apply font from the properties settings
                fontLabel.Font = WinForm.Properties.Settings.Default.evFont;
            }
        }
    }

0
投票

关于 Font 属性的不变性的评论帮助我解决了我的问题。

我的解决方案是在设置该属性时构造一个新的 Font 对象,但使用您存储的字体系列名称和大小来构造它。这可以确保您不会在 Height 属性中遇到烦人的异常。

这是我的解决方案的片段:

this.mainEditor.Font = new Font(Settings.Font.FontFamily.Name, Settings.Font.Size);

我在设置中存储了一个字体变量,但我只从中提取构建新字体模型所需的属性。

© www.soinside.com 2019 - 2024. All rights reserved.