1.自定义过滤控件属性的设计器类:
用法: [Designer(typeof(PropertiesFilterDesigner), typeof(IDesigner))]加到需要过滤的控件类前
/// <summary>
/// 自定义过滤控件属性的设计器类/// </summary>
public class PropertiesFilterDesigner : ControlDesigner
{
protected override void PreFilterProperties(IDictionary properties)
{
//取得设计时当前控件类型
Type type = base.Control.GetType();
PropertyInfo[] piArray = type.GetProperties();
foreach (PropertyInfo p in piArray)
{
//仅保留标有自定义特性CustomHelperAttribute("描述", true)的属性,必定需要保
//留只是少数咋们关心的属性,CustomHelperAttribute: Attribute,实现如下面。
Object[] caArray = p.GetCustomAttributes(typeof(CustomHelperAttribute), true);
if (caArray.Length > 0)
{
foreach (CustomHelperAttribute a in caArray)
{
//标有CustomHelperAttribute属性,但AllowShow = false 的属性移除
if (!a.AllowShow)
{
properties.Remove(p.Name);
}
}
}
else
{
//未标有CustomHelperAttribute属性移除
properties.Remove(p.Name);
}
}
base.PreFilterProperties(properties);
}
}
2. 自定义特性类: 用法简单,加在需要的地方都可以,如果是过滤属性,就在属性方法上加上咯。
/// <summary>
/// 自定义特性
/// </summary>
[AttributeUsage(AttributeTargets.All, AllowMultiple = false, Inherited = true)]
public class CustomHelperAttribute : Attribute
{
public CustomHelperAttribute(String Description, Boolean AllowShow)
{
this.description = Description;
this.allowShow = AllowShow;
}
protected String description;
/// <summary>
/// 描述信息
/// </summary>
public String Description
{
get
{
return this.description;
}
}
protected Boolean allowShow = true;
/// <summary>
/// 特殊用途,反射时会用到
/// </summary>
public Boolean AllowShow
{
get
{
return this.allowShow;
}
}
}