c# - 如何在 Visual Studio 中为字体类型使用 DefaultValueAtribute 类?

标签 c# vb.net winforms user-controls windows-forms-designer

我想知道我必须使用哪种正确的字符串语法来为 DefaultValueAtribute 指定值 Font 类型的类,以便在 Visual Studio 的设计器属性网格中将该值显示为非粗体。

这是我尝试过的:

C#:

public class MyControl : UserControl {

    [DefaultValue(typeof(Font), "Microsoft Sans Serif, 8.25pt")]
    public override Font Font {
        get { }
        set { }
    }
}

VB.NET:

Public Class MyControl : Inherits UserControl

    <DefaultValue(GetType(Font), "Microsoft Sans Serif, 8.25pt")>
    Public Overrides Property Font As Font
        ...
    End Property

End Class

...但是,默认字体字符串在我的控件的 Visual Studio 属性网格中显示为粗体

请注意,我显然是在搜索正确的解析字符串,而不是 ReflectionShouldSerializeFOO棘手的方法。

最佳答案

您似乎只是忘记将 Font 属性的初始值设置为默认值,因此该控件将使用其父字体,该字体与您期望的默认值不同,并以粗体显示.

你可以这样设置字体默认值:

using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
public partial class MyControl : UserControl
{
    private const string MyDefaultFont = "Tahoma, 10pt";
    public MyControl()
    {
        InitializeComponent();
        this.Font = (Font)new FontConverter().ConvertFromString(MyDefaultFont);
    }
    [DefaultValue(typeof(Font), MyDefaultFont)]
    public override Font Font
    {
        get { return base.Font; }
        set { base.Font = value; }
    }
}

注意 Control.Fontambient property如果您没有显式地为 Font 属性分配任何值,则它不会被序列化并且控件将使用其父 Font 属性。如果您希望某些控件使用与其父 Font 不同的字体,为其分配字体就足够了。因此,您似乎根本不需要为子控件分配任何默认字体。

关于c# - 如何在 Visual Studio 中为字体类型使用 DefaultValueAtribute 类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42873178/

相关文章:

c# - 为什么这种线程化方法不起作用?

c# - 如何在启动时处理表单显示顺序

c# - 如何在 C# 中正确多线程运行时调用的 DLL

c# - 在 Windows 服务中使用 Thread.Sleep()

c# - 有人想过以这种方式使用黑板模式吗?

c# - 如何从谷歌地图API获取城市和邮政编码?

c# - 编辑文件元数据 - 代码在 VB 中可以,但在 C# 中不行

vb.net - 用户控件在运行时自动调整大小

c# - 事件处理程序中的 "reentrant call to SetCurrentCellAddressCore"- 仅当单元格行索引和列索引相等时

c# - 从长度为 M 的未排序数组中搜索前 N 个已排序整数?