如何设计粗体标签控件

本文关键字:标签 控件 | 更新日期: 2023-09-27 18:16:04

我正在尝试创建一个Label控件,该控件使用粗体自动显示其文本。

我的环境是一个c# Windows窗体应用程序,使用。net 3.5, Visual Studio 2010 SP1, Windows 7 Professional, SP1, 32位处理器。

我当前的实现如下所示。

我对这个粗体标签控件的唯一要求是它的行为应该完全像标准的System.Windows.Forms.Label控件(无论是在编程上还是在WinForm设计器环境中),除了它使用粗体来绘制文本。

以下是我对当前实现的一些关注:

  1. 我打算在大型应用程序的许多地方使用这个粗体标签控件,从而在运行时产生数百个该控件的实例。我是否不必要地创建新的字体对象?这些Font对象应该被处理掉吗?如果是,什么时候?

  2. 我想确保,当我本地化我的应用程序(设置Localizable属性为真父容器),这个粗体标签将与WinForm资源序列化机制表现良好。换句话说,如果我将这个粗体标签放到Windows窗体上,然后将窗体的Localizable设置为true,然后单击Save, Visual Studio将把我的窗体的资源序列化到MyForm.Designer.cs中。这将包括我的粗体标签控件的一个实例。为粗体标签设置字体的实现会破坏这种资源序列化机制吗?

  3. 是否有更好/更干净的实现?还有其他问题需要考虑吗?

(代码遵循)

namespace WindowsFormsApplication1
{
using System.ComponentModel;
using System.Drawing;
/// <summary>
/// Represents a standard Windows label with a bolded font.
/// </summary>
public class BoldLabel : System.Windows.Forms.Label
{
    [Browsable( false )]
    [DesignerSerializationVisibility( DesignerSerializationVisibility.Hidden )]
    public override Font Font
    {
        get
        {
            Font currentFont = base.Font;
            if ( currentFont.Bold )
            {
                // Nothing to do, since the current font is already bold.
                //
                return currentFont;
            }
            if ( currentFont.FontFamily.IsStyleAvailable( FontStyle.Bold ) )
            {
                // The current font supports the bold style, so create
                // a bold version of the current font and return it.
                //
                return new Font( currentFont, FontStyle.Bold );
            }
            else
            {
                // The current font does NOT support the bold style, so
                // just return the current font.
                //
                return currentFont;
            }
        }
        set
        {
            // The WinForm designer should never set this font, but we
            // implement this method for completeness.
            //
            base.Font = value;
        }
    }
}
}

如何设计粗体标签控件

我不明白为什么这不能适用于所有的用例:

public partial class BoldLabel : Label
{
    public BoldLabel()
    {
        InitializeComponent();
        base.Font = new Font(base.Font, FontStyle.Bold);
    }
    public override Font Font
    {
        get
        {
            return base.Font;
        }
        set
        {
            base.Font = new Font(value, FontStyle.Bold);
        }
    }
}

处理正确序列化的关键是确保get操作总是便宜的,因此在set中进行工作。不应该担心创建太多的Font对象;它将创建与完成工作所需的完全相同的数量,并且GC将拾取任何剩余的(例如,set操作的value将在set完成后减少引用计数,然后GC将稍后处理它)。