首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> ASP.NET 基礎 >> 關於ASP.NET

ASP.NET 控件開發系列(七):ComponentEditor 組件編輯器實作屬性生成器

     編輯:關於ASP.NET

除了 PropertyGrid 的屬性視窗,Visual Studio 提供元件層級的 ComponentEditor(如 DataGrid 的「屬性產生器」),提供更豐富、符合業務邏輯的視覺化設定介面。

ComponentEditor 與 UITypeEditor 差異

維度UITypeEditorComponentEditor
作用對象單一屬性整個控件/元件
觸發方式屬性格點點擊下拉/彈出屬性視窗底部「屬性產生器」連結
回傳型別屬性值無(直接修改元件狀態)

實作步驟

1. 控件主類別標記

[Designer(typeof(MyDesigner))]
[Editor(typeof(MyComponentEditor), typeof(ComponentEditor))]
public class MyControl : WebControl { }

2. ComponentEditor 實作

public class MyComponentEditor : ComponentEditor
{
    public override bool EditComponent(ITypeDescriptorContext context, object component)
    {
        using (var form = new MyComponentEditorForm((MyControl)component))
        {
            return form.ShowDialog() == DialogResult.OK;
        }
    }
}

3. 編輯器視窗表單

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();
    }
}

關鍵設計要點

  • Designer 協助:設計器提供 ActionLists 可在設計介面右鍵選單加入「屬性產生器」捷徑
  • PropertyDescriptor.SetValue:而非直接指派屬性,支援設計階段 Undo/Redo
  • 表單初始化:建構式接收元件實例,反映當前屬性值
  • 驗證與錯誤處理:確認按鈕驗證輸入,錯誤時不關閉視窗

適用場景

  • 屬性間有複雜相依關係(如:啟用 A 時 B 必填)
  • 需要精靈式步驟設定(資料來源配置精靈)
  • 屬性數量龐大,分類管理更直觀
  • 需預覽即時效果(報表設計器、圖表設定)
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved