1. 程式人生 > >C# WinForm PropertyGrid用法

C# WinForm PropertyGrid用法

關於C# PropertyGrid的用法沒有找到,找到一個C++的用法。 模仿著使用了一下,感覺挺不錯,分享一下。 基本用法: 拖個PropertyGrid,繫結一個屬性類就行了。

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

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

        private void Form1_Load(object sender, EventArgs e)
        {
            propertyGrid1.SelectedObject = new Go();
        }

        class Go
        {
            private string _Hi = "hi";
            public string Hi
            {
                get { return _Hi; }
                set { _Hi = Hi; }
            }
        }

    }
}

它能自動識別Go類中的屬性,並且自動關聯。

對屬性進行分類並加註釋:

class Go
{
    private float _TieMu = 5.5f;
    private string _Rule = "數子法";
    [CategoryAttribute("規則"), DescriptionAttribute("貼目")]
    public float TieMu
    {
        get { return _TieMu; }
        set { _TieMu = TieMu; }
    }
    [CategoryAttribute("規則"), DescriptionAttribute("計演算法")]
    public string Rule
    {
        get { return _Rule; }
        set { _Rule = Rule; }
    }

    private int _Black = 0;
    private int _White = 0;
    [CategoryAttribute("圍棋"), DescriptionAttribute("黑")]
    public int Black
    {
        get { return _Black; }
        set { _Black = Black; }
    }
    [CategoryAttribute("圍棋"), DescriptionAttribute("白")]
    public int White
    {
        get { return _White; }
        set { _White = White; }
    }
}

使用Color型別可以顯示顏色選擇下拉框,使用Image型別可以顯示圖片選擇對話方塊,真強大。

private Color _BoardColor = Color.Yellow;
[CategoryAttribute("圍棋"), DescriptionAttribute("棋盤顏色")]
public Color BoardColor
{
    get { return _BoardColor; }
    set { _BoardColor = BoardColor; }
}

private Image _Background;
[CategoryAttribute("圍棋"), DescriptionAttribute("棋盤背景")]
public Image Background
{
    get { return _Background; }
    set { _Background = Background; }
}

另外是自定義型別,比如列舉.

參考: