Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

How to set the DefaultValue for the Font property

0.00/5 (No votes)
12 Feb 2006 1  
How to set the DefaultValue for the Font property.

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()

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here