Arvo Bowen
Arvo Bowen

Reputation: 4945

How can I create a User Control with the default font of it's parent?

I have created a new User Control that has a property like...

private Font m_DisplayFont;
public Font DisplayFont
{
    get { return m_DisplayFont; }
    set { m_DisplayFont = value; }
}

I want to set m_DisplayFont to the parent's font when I drop the new User Control into a container (Form, GroupBox, etc).

I currently have tried the following but can not get the parent when the class is constructed. Any suggested would be welcome. Thanks!

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using System.Reflection;

namespace MyTestControl
{
    public partial class UserControl1 : ProgressBar
    {
        private Font m_DisplayFont;
        public Font DisplayFont
        {
            get { return m_DisplayFont; }
            set { m_DisplayFont = value; }
        }

        public UserControl1()
        {
            InitializeComponent();

            object parent = base.Parent;
            m_DisplayFont = null;
            if (parent != null)
            {
                //See if parent contains a font
                Type type = parent.GetType();
                IList<PropertyInfo> props = new List<PropertyInfo>(type.GetProperties());
                foreach (PropertyInfo propinfo in props)
                {
                    if (propinfo.Name == "Font")
                    {
                        m_DisplayFont = (Font)propinfo.GetValue(parent, null);
                    }
                }
            }
            if (m_DisplayFont == null) m_DisplayFont = new Font("Verdana", 20.25f);
        }
    }
}

Upvotes: 0

Views: 856

Answers (1)

Eugene Podskal
Eugene Podskal

Reputation: 10401

You can use the ParentChanged event:

Occurs when the Parent property value changes.

private void ParentChanged(Object sender, EventArgs args)
{
    var parent = this.Parent;
    if (parent == null)
        return;

    var fontProp = parent
        .GetType()
        .GetProperty("Font");
    var font = (fontProp == null) ? 
        new Font("Verdana", 20.25f) : (Font)fontProp.GetValue(parent, null);
    this.m_DisplayFont = font;
}

Upvotes: 2

Related Questions