WINFROM.PropertyGrid学习小结

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.ComponentModel.Design.Serialization;
using System.Globalization;
using System.Reflection;
using System.Collections;
using System.ComponentModel.Design;
using System.Drawing.Design;

namespace ClassLibrary1
{
 
    public partial class UserControl2 : UserControl
    {
        public UserControl2()
        {
            InitializeComponent();
            this.BackColor = Color.FromArgb(88, 47, 50);
        }
        [Category("自定义属性"),Description("年龄"),Browsable(true)]
        public int Age { get; set; }
        [Category("自定义属性"),Description("全名"),Browsable(true)]
        public string  FullName { get; set; }
        [Category("自定义属性"), Description("性别"), Browsable(true)]
        public Gender Gender { get; set; }
        [Category("自定义属性"), Description("是否已婚"), Browsable(true)]
        public bool IsMarried { get; set; }
        [Category("自定义属性"), Description("地址,该属性提供简单下拉框"), Browsable(true)]
        [TypeConverter(typeof(AddressValues))]
        public string Address { get; set; }
        PersonalInfo personal = null;
        [Category("自定义属性"), Description("个人信息,该属性是复杂属性"), Browsable(true)]
        public PersonalInfo PersonalInfo
        {
            get
            {
                if (personal==null)
                {
                    return new PersonalInfo("No",0,0,"No");
                }
                else
                {
                    return personal;
                }
            }
            set
            {
                personal = value;
            }
        }

        MyNodeCollection _MyNodeCollection = new MyNodeCollection();
        /// <summary>
        /// 用于测试打开Collection Editor的编辑器窗体
        /// </summary>
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
        [Editor(typeof(MyCollectionEditor), typeof(UITypeEditor))]//属性编辑器
        [Category("自定义属性"), Description("地址,该属性是集合属性,其中包含复杂属性"), Browsable(true)]
        public MyNodeCollection MyNodeCollection
        {
            get
            {
                return _MyNodeCollection;
            }
            set
            {
                _MyNodeCollection = value;
            }
        }

    }
    public enum Gender
    {,}

    public class AddressValues:StringConverter
    {
        public override bool GetStandardValuesSupported(ITypeDescriptorContext context)
        {
            return true;
            return base.GetStandardValuesSupported(context);
        }
        public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context)
        {
            return new StandardValuesCollection(new string[] { "上海","苏州","南京","无锡" });
        }

    }
    [TypeConverter(typeof(PersonalInfoConverter))]
    public class PersonalInfo
    {
        public string FullName { get; set; }
        public int Age { get; set; }
        public double Height { get; set; }
        public string WorkType { get; set; }
        //public PersonalInfo() { }
        public PersonalInfo(string fullName, int age, double height, string workType)
        {
            this.FullName = fullName;
            this.Age = age;
            this.Height = height;
            this.WorkType = workType;
        }
    }
    public class PersonalInfoConverter : TypeConverter
    {
        public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
        {
            return sourceType == typeof(string) || base.CanConvertFrom(context, sourceType);
        }
        public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
        {
            return destinationType == typeof(InstanceDescriptor) || base.CanConvertTo(context, destinationType);
        }
        public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
        {
            string text = value as string;
            if (text == null)
            {
                return base.ConvertFrom(context, culture, value);
            }
            string text2 = text.Trim();
            if (text2.Length == 0)
            {
                return null;
            }
            if (culture == null)
            {
                culture = CultureInfo.CurrentCulture;
            }
            char separator = culture.TextInfo.ListSeparator[0];
            string[] array = text2.Split(new char[] { separator }, StringSplitOptions.None);
            //int[] array2 = new int[array.Length];
            //TypeConverter converter = TypeDescriptor.GetConverter(typeof(int));
            //for (int i = 0; i < array2.Length; i++)
            //{
            //    array2[i] = (int)converter.ConvertFromString(context, culture, array[i]);
            //}
            if (array.Length == 4)
            {
                string fullName = array[0];
                int age = int.Parse(array[1]);
                double height = double.Parse(array[2]);
                string worType = array[3];
                var instance = new PersonalInfo(fullName, age, height, worType);
                return instance;

            }
            throw new ArgumentException("111");
        }

        public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
        {
            if (destinationType == null)
            {
                throw new ArgumentNullException("destinationType");
            }
            if (value is PersonalInfo)
            {
                PersonalInfo personal = (PersonalInfo)value;
                if (destinationType == typeof(string))
                {
                    if (culture == null)
                    {
                        culture = CultureInfo.CurrentCulture;
                    }
                    string separator = culture.TextInfo.ListSeparator + " ";
                    TypeConverter converter = TypeDescriptor.GetConverter(typeof(object));
                    string[] value2 = new string[]
                    {
                            converter.ConvertToString(context, culture, personal.FullName),
                            converter.ConvertToString(context, culture, personal.Age),
                            converter.ConvertToString(context,culture,personal.Height),
                            converter.ConvertToString(context,culture,personal.WorkType)
                    };
                    return string.Join(separator, value2);
                }
                if (destinationType == typeof(InstanceDescriptor))
                {
                    ConstructorInfo constructor = typeof(PersonalInfo).GetConstructor(new Type[]
                    {
                    typeof(string),
                    typeof(int),
                    typeof(double),
                    typeof(string)

                    });
                    if (constructor != null)
                    {
                        return new InstanceDescriptor(constructor, new object[]
                        {
                        personal.FullName,
                        personal.Age,
                        personal.Height,
                        personal.WorkType
                        });
                    }
                }


            }
            return base.ConvertTo(context, culture, value, destinationType);
        }
        public override object CreateInstance(ITypeDescriptorContext context, IDictionary propertyValues)
        {
            if (propertyValues == null)
            {
                throw new ArgumentNullException("propertyValues");
            }
            object obj = propertyValues["FullName"];
            object obj2 = propertyValues["Age"];
            object obj3 = propertyValues["Height"];
            object obj4 = propertyValues["WorkType"];
            if (obj == null || obj2 == null || obj3 == null || obj4 == null || !(obj is string) || !(obj2 is int) || !(obj3 is double) || !(obj4 is string))
            {
                throw new ArgumentException("111");
            }
            var instance = new PersonalInfo((string)obj, (int)obj2, (double)obj3, (string)obj4);
            return instance;
        }
        public override bool GetCreateInstanceSupported(ITypeDescriptorContext context)
        {
            return true;
        }
        public override PropertyDescriptorCollection GetProperties(ITypeDescriptorContext context, object value, Attribute[] attributes)
        {

            PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(PersonalInfo), attributes);
            return properties.Sort(PersonalInfoConverter.s_propertySort);

        }
        public override bool GetPropertiesSupported(ITypeDescriptorContext context)
        {
            return true;
        }
        private static readonly string[] s_propertySort = new string[] { "FullName", "Age", "Height", "WorkType" };

    }

    /// <summary>
    /// 自定义CollectionEditor编辑器
    /// </summary>
    public class MyCollectionEditor : CollectionEditor
    {
        public MyCollectionEditor(Type type)
        : base(type)
        { }

        protected override bool CanRemoveInstance(object value)
        {
            return false; ;
        }

        /// <summary>
        /// 限制一次选一个实例
        /// </summary>
        /// <returns></returns>
        protected override bool CanSelectMultipleInstances()
        {
            return false;
        }
        protected override CollectionForm CreateCollectionForm()
        {
            CollectionForm frm = base.CreateCollectionForm();
            frm.AcceptButton.PerformClick();
            FieldInfo fileinfo = frm.GetType().GetField("propertyBrowser", BindingFlags.NonPublic | BindingFlags.Instance);
            if (fileinfo != null)
            {
                (fileinfo.GetValue(frm) as System.Windows.Forms.PropertyGrid).HelpVisible = true;
            }
            frm.Width = 700;
            frm.Height = 600;
            return frm;
        }
        /// <summary>
        /// 指定创建的对象类型
        /// </summary>
        /// <returns></returns>
        protected override Type CreateCollectionItemType()
        {
            return typeof(Employee);
        }
        protected override object CreateInstance(Type itemType)
        {
            //创建一个实例
            //Size o = (Size)itemType.Assembly.CreateInstance(itemType.FullName);
            //o.Width = 25;
            //o.Height = 25;
            Employee o = new Employee();
            //IDesignerHost host = (IDesignerHost)this.GetService(typeof(IDesignerHost));
            //host.Container.Add(o);//重要!自动生成组件的设计时代码!

            //或者:
            //this.Context.Container.Add(o);//重要!自动生成组件的设计时代码!

            return o;
        }
        protected override void DestroyInstance(object instance)
        {
            base.DestroyInstance(instance);//重要!自动删除组件的设计时代码!
        }

        //protected override Type[] CreateNewItemTypes()
        //{
        //    return new Type[]
        //    {
        //      typeof(Panel),
        //      typeof(Button),
        //      typeof(TextBox)
        //    };
        //}
        protected override string GetDisplayText(object value)
        {

            Employee item = new Employee();
            item = (Employee)value;
            return base.GetDisplayText(string.Format("{0}", item.Name));
        }

        protected override object[] GetItems(object editValue)
        {
            MyNodeCollection myNodeCollection = (MyNodeCollection)editValue;

            return myNodeCollection.ToArry();
        }
    }

    /// <summary>
    /// 自定义BaseCollection对象集合,实现IList接口
    /// 如Object Collection Editor窗体的Add/Delete钮不可用是因为没有实现IList接口
    /// </summary>
    public class MyNodeCollection : BaseCollection, IList
    {
        private ArrayList _innerList;

        public MyNodeCollection()
        {
            _innerList = new ArrayList();
        }

        protected override ArrayList List
        {
            get
            {
                return (ArrayList)_innerList;
            }
        }
        public override int Count
        {
            get { return _innerList.Count; }
        }



        #region IList Members

        public int Add(object value)
        {
            return this.List.Add(value);
        }

        public void Clear()
        {
            this.List.Clear();
        }

        public bool Contains(object value)
        {
            return this.List.Contains(value);
        }

        public int IndexOf(object value)
        {
            return this.List.IndexOf(value);
        }

        public void Insert(int index, object value)
        {
            this.List.Insert(index, value);
        }

        public bool IsFixedSize
        {
            get { return this.List.IsFixedSize; }
        }

        public void Remove(object value)
        {
            this.List.Remove(value);
        }

        public void RemoveAt(int index)
        {
            this.List.RemoveAt(index);
        }

        public object this[int index]
        {
            get
            {
                return List[index];
            }
            set
            {
                List[index] = value;
            }
        }
        public object[] ToArry()
        {
            return _innerList.ToArray();
        }
        #endregion
    }

    public class Employee
    {
        [Category("基本属性")]
        [DisplayName("员工姓名")]
        [Description("员工姓名")]
        public string Name { get; set; }


        [Category("基本属性")]
        [DisplayName("姓别")]
        [Description("姓别")]
        public EnumGender Gender { get; set; }
        [Category("基本属性")]
        [DisplayName("尺寸")]
        [Description("尺寸")]

        public Size InnerSize { get; set; }
        [Category("基本属性")]
        [DisplayName("人员信息")]
        [Description("人员信息")]
        public PersonalInfo PersonalInfo { get; set; } = new PersonalInfo("No", 0, 0, "No");


    }

    public enum EnumGender
    {= 0,,
    };

}

效果如下图:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值