我创建了一个新的用户控件,其属性如...
private Font m_DisplayFont;
public Font DisplayFont
{
get { return m_DisplayFont; }
set { m_DisplayFont = value; }
}
当我将新的用户控件放入容器(Form,GroupBox等)时,我想将m_DisplayFont设置为父字体。
我目前已尝试过以下内容,但在构造类时无法获取父级。任何建议都会受到欢迎。谢谢!
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);
}
}
}
答案 0 :(得分:2)
您可以使用package.json事件:
在Parent属性值更改时发生。
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;
}