c# 在PropertyGrid上显示类的属性

当我们使用PropertyGrid控件时,平时用的都是常见的类型如:int ,string,bool通过如下代码可以将这个类的属性显示在Propertygrid

   public partial class Form1 : Form
    	{
    		public Form1()
    		{
    			InitializeComponent();
    			Student stu = new Student();
    			proGrid.SelectedObject = stu;
    		}
    	}
    
    	public class Student
    	{
    		private string name = "Tom";
    		public string Name
    		{
    			get
    			{
    				return name;
    			}
    			set
    			{
    				name = value;
    			}
    		}
    
    		private int stuID = 05;
    		public int StuID
    		{
    			get
    			{
    				return stuID;
    			}
    			set
    			{
    				stuID = value;
    			}
    		}
    		private bool isBoy = true;
    		public bool IsBoy
    		{
    			get
    			{
    				return isBoy;
    			}
    			set
    			{
    				isBoy = value;
    			}
    		}
    	}

效果如下图
c# 在PropertyGrid上显示类的属性_第1张图片

问题来了:如果我们在Student类中定义一个类类型的属性呢?

解决方法: 在我们的类类型的属性上方添加[TypeConverter(typeof(ExpandableObjectConverter))]
先创建一个Lily

public class Lily
	{
		private int stuID = 04;
		public int StuID
		{
			get
			{
				return stuID;
			}
			set
			{
				stuID = value;
			}
		}
		private string name = "Lily";
		public string Name
		{
			get
			{
				return name;
			}
			set
			{
				name = value;
			}
		}
		public override string ToString()
		{
			return "...";
		}
	}

接下来是类类型的代码“

public class Student
	{
	    //名字
		private string name = "Tom";
		public string Name
		{
			get
			{
				return name;
			}
			set
			{
				name = value;
			}
		}
       //ID
		private int stuID = 05;
		public int StuID
		{
			get
			{
				return stuID;
			}
			set
			{
				stuID = value;
			}
		}
		//是否是男孩
		private bool isBoy = true;
		public bool IsBoy
		{
			get
			{
				return isBoy;
			}
			set
			{
				isBoy = value;
			}
		}
		//Lily类型
		Lily myLily = new Lily();
		[TypeConverter(typeof(ExpandableObjectConverter))] 
		[EditorBrowsable(EditorBrowsableState.Always)]
		public Lily MyLily
		{
			get
			{
				return myLily;
			}
			set
			{
				myLily = value;
			}
		}
	}

效果图如下:
c# 在PropertyGrid上显示类的属性_第2张图片

本文参考自 https://www.codeproject.com/Articles/271589/Show-Properties-of-a-Class-on-a-PropertyGrid

你可能感兴趣的:(c# 在PropertyGrid上显示类的属性)