我正在尝试创建一个标签控件,该控件使用粗体字体自动显示其文本。
我的环境是一个C# Windows应用程序,使用.NET 3.5、Visual 2010 SP1、Windows7Professional、SP1、32位处理器。
我目前的实现如下所示。
我对这个粗体标签控件的唯一要求是,它的行为应该与标准的System.Windows.Forms.Label控件完全一样(无论是以编程方式还是在WinForm designer环境中),除非它使用粗体字体来绘制文本。
下面是我对当前实现的一些关注:
代码如下
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;
}
}
}
}发布于 2011-11-28 18:49:40
我不明白为什么这不适用于所有用例:
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的set操作将减少引用计数,然后GC将在稍后处理它)。
https://stackoverflow.com/questions/8300499
复制相似问题