如何使用其父级的默认字体创建用户控件?

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

我创建了一个新的用户控件,它有一个 属性 比如...

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

我想在将新用户控件放入容器(Form、GroupBox 等)时将 m_DisplayFont 设置为父级字体。

我目前尝试了以下方法,但在构造 class 时无法获取父对象。欢迎任何建议。谢谢!

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

您可以使用 ParentChanged 事件:

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