C# WinForm PropertyGrid 控件的基本用法
▲ 界面
搞个类测试一下:
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
属性可取值可赋值。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了