当我们使用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;
}
}
}
效果如下图
问题来了:如果我们在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;
}
}
}
效果图如下:
本文参考自 https://www.codeproject.com/Articles/271589/Show-Properties-of-a-Class-on-a-PropertyGrid