Introduction
This article tells you about solving a very common problem in Visual Studio .NET 2003! You know that we could set the default value for some properties with the DefaultValue
attribute, such as in the below command:
[System.ComponentModel.DefaultValue(...)]
But if you want to set the default value for the Font
property in this manner, you will see a very abnormal behavior and it doesn't work! Because, the Font
property is not a simple property. I spent some time to solve this problem, and at last, I got the solution...
Scenario: Suppose that you want to create a button that is inherited from Microsoft Button
, and you want to set the default value of the Font
property to Tahoma with an 8 point size.
Solution: The below example will tell you how to do that:
public class Button : System.Windows.Forms.Button
{
private static System.Drawing.Font _defaultFont =
new System.Drawing.Font("Tahoma",
8.25f, System.Drawing.FontStyle.Regular,
System.Drawing.GraphicsUnit.Point,
178,
false);
public override System.Drawing.Font Font
{
get
{
return(base.Font);
}
set
{
if(value == null)
base.Font = _defaultFont;
else
{
if(value == System.Windows.Forms.Control.DefaultFont)
base.Font = _defaultFont;
else
base.Font = value;
}
}
}
public override void ResetFont()
{
Font = null;
}
private bool ShouldSerializeFont()
{
return(!Font.Equals(_defaultFont));
}
public Button()
{
Font = _defaultFont;
}
}
As you see in the above code, I did not write any attributes for the Font
property, and instead, I used two methods with the names of ResetFont()
and ShouldSerializeFont()
. You should know that for each property in .NET, we have these two methods:
ResetSomeProperty()
ShouldSerializeSomeProperty()