簡體   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