PropertyGrid显示下拉列表

/**********************Form1.cs****************************/

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            Student stu = new Student();
            stu.Gender ="男,女";
            stu.AllGender = stu.Gender;//提供所有选项
            //stu.Gender ="1,2,3";
            propertyGrid1.SelectedObject = stu;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            var stu = propertyGrid1.SelectedObject as Student;
            MessageBox.Show(stu.Gender);
        }
    }
}

/****************************Student.cs***********************************************/

    public class Student
    {
        [Category("性别"), Description("student gender"),
       TypeConverter(typeof(GenderConverter))]
        public string Gender
        {
            get;
            set;
        }

        //提供所有选项,通过转换后呈现出来
        [Browsable(false)]
        public string AllGender
        {
            get;
            set;
        }
    }

/***************************************************************/

  public class GenderConverter : StringConverter
    {

        public override string ToString()
        {
            return "";
        }
   
        //true enable,false disable
        public override bool GetStandardValuesSupported(ITypeDescriptorContext context)
        {
            return true;
        }

扫描二维码关注公众号,回复: 9593492 查看本文章

        public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context)
        {
            var student = context.Instance as Student;
            return new StandardValuesCollection(student.AllGender.Split(',').ToList());
            //return new StandardValuesCollection(new string[] { "男", "女" }); //编辑下拉框中的items
        }

        //true: disable text editting.    false: enable text editting;
        public override bool GetStandardValuesExclusive(ITypeDescriptorContext context)
        {
            return true;
        }
    }

发布了488 篇原创文章 · 获赞 73 · 访问量 30万+

猜你喜欢

转载自blog.csdn.net/dxm809/article/details/104481880
今日推荐