搞个类测试一下:
class Student
{
[CategoryAttribute("学生信息"), DescriptionAttribute("姓名")]
public string Name { get; set; }
[CategoryAttribute("学生信息"), DescriptionAttribute("年龄")]
public int Age { get; set; }
[CategoryAttribute("学生信息"), DescriptionAttribute("性别")]
public string Sex { get; set; }
[CategoryAttribute("学生成绩"), DescriptionAttribute("语文")]
public int Chinese { get; set; }
[CategoryAttribute("学生成绩"), DescriptionAttribute("英语")]
public int English { get; set; }
[CategoryAttribute("学生成绩"), DescriptionAttribute("数学")]
public int Math { get; set; }
}
界面后台:
public partial class FormMain : Form
{
private Student _xiaoMing = null;
public FormMain()
{
InitializeComponent();
_xiaoMing = new Student() { Name = "小明", Age = 9, Sex = "男", Chinese = 100, English = 98, Math = 120 };
propertyGrid1.SelectedObject = _xiaoMing ;
}
private void btnShow_Click(object sender, EventArgs e)
{
MessageBox.Show($"姓名:{_xiaoMing.Name} 年龄:{_xiaoMing.Age} 性别:{_xiaoMing.Sex}\n语文:{_xiaoMing.Chinese} 英语:{_xiaoMing.English} 数学:{_xiaoMing.Math}" );
}
// 这一步手动其实没啥用,修改属性值后是直接影响的。
private void btnModify_Click(object sender, EventArgs e)
{
Student student = propertyGrid1.SelectedObject as Student;
_xiaoMing = student;
}
}
▲ 运行后直接显示了
控件的值其实和 SelectedObject
对象成一个绑定的关系,修改控件的值就相当于修改了SelectedObject
的值,类似于 WPF 的绑定。
如果类型不匹配会弹窗提示:
这样还是挺方便的。另外,SelectedObject
属性可取值可赋值。
我的公众号: