除了 PropertyGrid 的屬性視窗,Visual Studio 提供元件層級的 ComponentEditor(如 DataGrid 的「屬性產生器」),提供更豐富、符合業務邏輯的視覺化設定介面。
| 維度 | UITypeEditor | ComponentEditor |
|---|---|---|
| 作用對象 | 單一屬性 | 整個控件/元件 |
| 觸發方式 | 屬性格點點擊下拉/彈出 | 屬性視窗底部「屬性產生器」連結 | 回傳型別 | 屬性值 | 無(直接修改元件狀態) |
[Designer(typeof(MyDesigner))]
[Editor(typeof(MyComponentEditor), typeof(ComponentEditor))]
public class MyControl : WebControl { }
public class MyComponentEditor : ComponentEditor
{
public override bool EditComponent(ITypeDescriptorContext context, object component)
{
using (var form = new MyComponentEditorForm((MyControl)component))
{
return form.ShowDialog() == DialogResult.OK;
}
}
}
public class MyComponentEditorForm : Form
{
private MyControl _control;
public MyComponentEditorForm(MyControl control)
{
InitializeComponent();
_control = control;
// 用控件屬性初始化表單控件
txtProperty1.Text = _control.Property1;
}
private void btnOK_Click(object sender, EventArgs e)
{
// 使用 PropertyDescriptor 支援 Undo
var props = TypeDescriptor.GetProperties(_control);
props["Property1"].SetValue(_control, txtProperty1.Text);
// ... 其他屬性
DialogResult = DialogResult.OK;
Close();
}
}
ActionLists 可在設計介面右鍵選單加入「屬性產生器」捷徑