摘要:Windows Form的PropertyGrid控制項
一般在使用Visual Studio 2008開發工具的時候,常常都會用到屬性視窗,不過屬性視窗的元件其實在Windows Form也有提供,可以在工具箱找到,叫作PropertyGrid
其實使用方法相當簡單,只要將他拖拉到Form上面就會呈現一個空的PropertyGrid物件,並將屬性Dock設定成 Fill的值,就會變成下面的樣子
接著就是要建立PropertyGrid裡面的欄位資料,所以在這邊我們先定義一個簡單的類別,這是用來設定所有的欄位:
public class PropertyGridField
{
public string Column_A { get; set; }
public string Column_B { get; set; }
[Browsable(false)]
public string Column_C { get; set; }
}
這邊有用到Browsable的屬性(Attribute),可以透過此屬性來設定是否要將Column_C顯示到 PropertyGrid,不過在顯示之前,我們要將PropertyGridField的類別綁繫到PropertyGrid控制項上,所以可以透過PropertyGrid的SelectedObject屬性來設定,如下在Form1的建構子裡面加入下面的程式碼:
propertyGrid1.SelectedObject = new PropertyGridField();
這時候就可以執行看到綁繫後的PropertyGrid,並且只有顯示Column_A和Column_B
當然我們可能會常常看到PropertyGrid可以有按鈕顯示或是下拉選單,這時候就要透過Editor的Attrubute來定義,例如在Column_A的屬性上面定義Editor,如下面的程式碼:
[Editor(typeof(ImageEditor), typeof(UITypeEditor))]
public string Column_A { get; set; }
在Editor的Attrubute裡面傳入了兩個參數,第一個就是要在Column_A欄位顯示的設計視窗,例如在這邊是使用.NET內建的System.Drawing.Design.ImageEditor,可以用來開窗選擇圖片;第二個欄位是用來當作索引鍵,但是必須是第一個參數的父類別,通常會使用System.Drawing.Design.UITypeEditor來表示。所以畫面就會向下面一樣:
點選「...」的按鈕後就會出現一個檔案選擇的視窗,當然我也可以自訂自己的開窗方式,不過類別必須要實作UITypeEditor,在此類別內提供了幾個方法
- EditValue方法:取得自訂視窗所選擇的值。
- GetEditStyle方法:通知編輯樣式要顯示的選擇方式,例如提供按鈕或是下拉選單。
- GetPaintValueSupported方法:指出編輯器支援顯示數值的表示。
- PaintValue方法:用來呈現屬性值的外觀樣式。
public class TestPopPropertyEditor : UITypeEditor
{
public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext pContext)
{
if (pContext != null && pContext.Instance != null)
{
//以「...」按鈕的方式顯示
//UITypeEditorEditStyle.DropDown 下拉選單
//UITypeEditorEditStyle.None 預設的輸入欄位
return UITypeEditorEditStyle.Modal;
}
return base.GetEditStyle(pContext);
}
public override object EditValue(ITypeDescriptorContext pContext, IServiceProvider pProvider, object pValue)
{
IWindowsFormsEditorService editorService = null;
if (pContext != null && pContext.Instance != null && pProvider != null)
{
editorService = (IWindowsFormsEditorService)pProvider.GetService(typeof(IWindowsFormsEditorService));
if (editorService != null)
{
//將顯示得視窗放在這邊,並透過ShowDialog方式來呼叫
//取得到的值再回傳回去
MessageBox.Show("sfsf");
}
}
return pValue;
}
}
這時候我們將PropertyGridField的Column_B欄位設定成TestPopPropertyEditor,所以修改後的程式碼就會變成下面:
public class PropertyGridField
{
[Editor(typeof(ImageEditor), typeof(UITypeEditor))]
public string Column_A { get; set; }
[Editor(typeof(TestPopPropertyEditor), typeof(UITypeEditor))]
public string Column_B { get; set; }
[Browsable(false)]
public string Column_C { get; set; }
}
然而顯示的畫面就會變成下面的樣子,在Column_B欄位多了一個「...」按鈕,並且點選後會出現一個對話視窗: