C#中使用Property Grid(屬性面板)控制項

來源:互聯網
上載者:User

1.將Property Grid 控制項添加到工具箱中

由於預設情況下Property Grid 控制項沒有顯示在工具箱中所以需要手動添加。

 

圖1 將Property Grid添加到工具箱(在工具箱上右鍵選擇添加/移除項)

 

圖2 在自訂工具箱對話方塊中選中PropertyGrid控制項

2.編寫自訂類,並跟PropertyGrid控制項進行綁定

using System;
using System.ComponentModel;

namespace PropertyGridDemo
{
 [DefaultPropertyAttribute("Name")]
 public class Customer
 {
  private string name;
  private string email;
  private string mark;

  [CategoryAttribute("使用者資訊"), DescriptionAttribute("設定消費者姓名")]
  public string Name
  {
   get
   {
    return name;
   }
   set
   {
    name = value;
   }
  }

  [CategoryAttribute("使用者資訊"), DescriptionAttribute("設定消費者Email地址")]
  public string Email
  {
   get
   {
    return email;
   }
   set
   {
    email = value;
   }
  }

 [CategoryAttribute("備忘"), DescriptionAttribute("備忘資訊")]
  public string Mark
  {
   get
   {
    return mark;
   }
   set
   {
    mark = value;
   }
  }
 
  public Customer()
  {
  }
 }
}

首先定義自訂類型的時候要引用System.ComponentModel命名空間,將使用到該命名空間中的一些Attribute類,在上面的例子中主要使用了DefaultPropertyAttribute,CategoryAttribute和DescriptionAttribute三個Attribute。

DefaultPropertyAttribute       指定組件的預設屬性。

CategoryAttribute      指定當屬性或事件顯示在被一個設定為按分類順序模式的 System.Windows.Forms.PropertyGrid 控制項中時,用於給屬性或事件分組的類別的名稱。
DescriptionAttribute 指定屬性或事件的說明。

在編寫自定類的時候所有的屬性都應該有get 和set方法,如果沒有get方法那麼這個屬性在PropertyGrid中不顯示,沒有set方法的話則為唯讀屬性在PropertyGrid中無法設定該屬性的值。

將自訂類與PropertyGrid控制項進行綁定

使用PropertyGrid類的SelectedObject屬性進行綁定

private void Form1_Load(object sender, System.EventArgs e)
  {
   Customer customer = new Customer();
   customer.Name = "張三";
   customer.Email = "zhangsan@sina.com";

   propertyGrid1.SelectedObject = customer;
  }

運行結果:

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.