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

ASP.NET 控件開發系列(五):TypeConverter 與 PropertyTab 自訂屬性分頁

     編輯:關於ASP.NET

TypeConverter 不僅處理型別轉換,還能透過 PropertyTab 將屬性分類到自訂分頁,配合 PropertyDescriptor 實現精細的設計時屬性呈現控制。

自訂 PropertyTab 實作

[PropertyTab(typeof(MyPropertyTab), PropertyTabScope.Component)]
public class MyControl : WebControl { }

internal class MyPropertyTab : PropertyTab
{
    public override string TabName => "我的分頁";

    public override Bitmap Bitmap => new Bitmap(typeof(MyPropertyTab), "MyPropertyTab.bmp");  // 16x16 嵌入資源

    public override bool CanExtend(object extendee) => extendee is MyControl;

    public override PropertyDescriptorCollection GetProperties(ITypeDescriptorContext context, object component, Attribute[] attrs)
    {
        var ctrl = (MyControl)component;
        var list = new ArrayList();

        // 動態建立屬性描述器
        list.Add(new MyPropertyDescriptor(this, "Property1", typeof(int), ctrl));
        // ... 更多屬性

        return new PropertyDescriptorCollection((PropertyDescriptor[])list.ToArray(typeof(PropertyDescriptor)));
    }
}

自訂 PropertyDescriptor

private class MyPropertyDescriptor : PropertyDescriptor
{
    private MyPropertyTab _owner;
    private MyControl _target;
    private string _propertyName;

    public MyPropertyDescriptor(MyPropertyTab owner, string name, Type type, MyControl target)
        : base(name, new Attribute[] { CategoryAttribute.Data, RefreshPropertiesAttribute.All })
    {
        _owner = owner; _target = target; _propertyName = name;
    }

    public override Type PropertyType => typeof(int);
    public override Type ComponentType => typeof(MyControl);
    public override bool IsReadOnly => false;

    public override object GetValue(object component) => _target.GetType().GetProperty(_propertyName).GetValue(_target);
    public override void SetValue(object component, object value) => _target.GetType().GetProperty(_propertyName).SetValue(_target, value);
    public override void ResetValue(object component) { }
    public override bool CanResetValue(object component) => false;
    public override bool ShouldSerializeValue(object component) => false;
}

PropertyTabScope 三種範圍

值說明
Component當前元件專用
Document當前文件專用
Global全域,需父元件顯式移除
Static靜態,不可移除

RefreshPropertiesAttribute 控制屬性變更後刷新行為

  • All:屬性改變時整個屬性視窗重新整理
  • Repaint:僅重繪屬性格
  • Default:不自動刷新

應用場景

  • 屬性眾多時分組管理(如「資料」、「外觀」、「行為」、「進階」)
  • 特定模式下才顯示的屬性集合
  • 提供比預設「屬性/事件」雙分頁更符合業務的分類
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved