繁体   English   中英

如何设计Bold Label控件?

[英]How to design a Bold Label control?

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

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

我目前的实施如下所示。

我对这个粗体Label控件的唯一要求是它的行为应该与标准的System.Windows.Forms.Label控件(编程方式和WinForm设计器环境中)完全相同,除了它使用粗体字体绘制的事实它的文字。

以下是我对当前实现的一些担忧:

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

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

  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将获取任何剩余部分(例如,设置操作的value将在设置完成后减少引用计数,然后GC将在以后处理它)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM