C# 设计控件时,过滤掉大部分属性,仅保留关心的属性

本文介绍了如何在C#中自定义设计器类`PropertiesFilterDesigner`来过滤控件属性,只显示关心的部分。通过在控件类前使用`[Designer(typeof(PropertiesFilterDesigner), typeof(IDesigner))]`进行标记,并结合`CustomHelperAttribute`特性,可以轻松控制哪些属性在设计时可见。`CustomHelperAttribute`允许设置描述信息和是否显示的标志,便于属性的筛选。" 124099676,8748443,DVC 数据版本控制指南,"['大数据', '版本控制', '机器学习', '数据管理']

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

   

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



评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值