首先定義一個要在下拉框顯示的控件:
using System;
using System.Windows.Forms;
namespace Simon.WinForms.Examples.PropertyGrid
{
public class EditorControl : UserControl
{
public EditorControl()
{
this.label1 = new System.Windows.Forms.Label();
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(21, 24);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(41, 12);
this.label1.TabIndex = 0;
this.label1.Text = "名稱:";
this.comboBox1 = new System.Windows.Forms.ComboBox();
this.comboBox1.FormattingEnabled = true;
this.comboBox1.Items.AddRange(new object[] {
"名稱一",
"名稱二",
"名稱三",
"名稱四"});
this.comboBox1.Location = new System.Drawing.Point(56, 21);
this.comboBox1.Name = "comboBox1";
this.comboBox1.Size = new System.Drawing.Size(133, 20);
this.comboBox1.TabIndex = 2;
this.comboBox1.SelectedIndexChanged += new System.EventHandler(this.comboBox1_SelectedIndexChanged);
this.SuspendLayout();
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.Controls.Add(this.comboBox1);
this.Controls.Add(this.label1);
this.Name = "EditorControl";
this.Size = new System.Drawing.Size(210, 64);
this.ResumeLayout(false);
this.PerformLayout();
}
private Label label1;
private ComboBox comboBox1;
public string result = "";
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
result = comboBox1.SelectedItem.ToString();
}
}
}
從System.Drawing.Design.UITypeEditor繼承一個自定義屬性編輯管理器類,參考如下:
using System.Drawing.Design;
using System.Windows.Forms.Design;
namespace Simon.WinForms.Examples.PropertyGrid
{
public class Editor : UITypeEditor
{
public override UITypeEditorEditStyle GetEditStyle(System.ComponentModel.ITypeDescriptorContext context)
{
// 編輯屬性值時,在右側顯示...更多按鈕
return UITypeEditorEditStyle.Modal;
}
public override object EditValue(System.ComponentModel.ITypeDescriptorContext context, System.IServiceProvider provider, object value)
{
var edSvc = provider.GetService(typeof(IWindowsFormsEditorService)) as IWindowsFormsEditorService;
if (edSvc != null)
{
var popedControl = new EditorControl();
// 還有ShowDialog這種方式,可以彈出一個窗體來進行編輯
edSvc.DropDownControl(popedControl);
value = popedControl.result;
}
return base.EditValue(context, provider, value);
}
}
}
定義一個使用PropertyGrid顯示屬性的類型。using System.ComponentModel;
namespace Simon.WinForms.Examples.PropertyGrid
{
public class ShowedClass
{
[DisplayName("名稱")]
[Editor(typeof(Editor), typeof(System.Drawing.Design.UITypeEditor))]
public string Name { get; set; }
[Editor(typeof(Editor), typeof(System.Drawing.Design.UITypeEditor))]
public string Description { get; set; }
}
}
在窗體上放好PropertyGrid,然後把你的類實例化後讓PropertyGrid來顯示設置就可以看到效果了。
propertyGrid1.SelectedObject = new ShowedClass() { Name="我沒名字"};