2011-11-28 56 views
4

我正在嘗試創建一個標籤控件,該控件使用粗體字自動顯示其文本。如何設計一個Bold 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。這將包括我大膽的標籤控制的一個實例。我爲我的粗體標籤設置字體的實現是否搞砸了這個資源序列化機制?

  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; 
     } 
    } 
} 
} 

回答

5

我不明白爲什麼這會不會對你的所有用例的工作:

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將在稍後處理它)。

+0

問題:您似乎在創建UserControl(因爲您有部分限定符和InitializeComponent調用),而不是直接從Label中派生。不必要。更糟糕的是,你的實現在構造函數中設置字體一次。對父字體的更改不會自動傳播到BoldLabel(它們在我的實現中執行)。通過創建一個新窗體,在窗體上放置一個BoldLabel,然後在WinForm設計器屬性面板中更改窗體的字體來嘗試它。最後,您的實現會導致BoldLabel.Font屬性在Form.Designer.cs中顯式設置。 – ahazzah

相關問題