首页 > Windows开发 > 详细

WinForm_根据类的属性利用反射动态创建Label

时间:2020-04-01 16:12:25      阅读:76      评论:0      收藏:0      [点我收藏+]

Class:

    class Recipe
    {
        public int ID { get; set; }
        public string RecipeName { get; set; }
        public string Comment { get; set; }
        public string Quantity { get; set; }
        public string con1 { get; set; }
        public string con2 { get; set; }
        public string con3 { get; set; }
    }

现在根据con1,con2 和 con3 动态创建三个label.

            int X = 75, Y = 65, i = 0;
            Recipe recipe = new Recipe { ID = 1, con1 = "p1", con2 = "p2", con3 = "p3" };
            foreach (var prop in recipe.GetType().GetProperties())
            {
                if (prop.Name.StartsWith("con"))
                {
                    var value = prop.GetValue(recipe);
                    if (value != null)
                    {
                        Label label = new Label()
                        {
                            AutoSize = true,
                            MaximumSize = new Size(300, 150),
                            MinimumSize = new Size(300, 10),
                            Location = new Point(X, Y + 20 * i),
                            Text = value.ToString()
                        };
                        i++;
                        Controls.Add(label);
                    }
                }
            }

测试结果:

技术分享图片

WinForm_根据类的属性利用反射动态创建Label

原文:https://www.cnblogs.com/xingyz/p/12612533.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!