Cracker 's Blog

Now, flutter and fly For own goal. No longer be puerility.
  博客园  :: 首页  :: 新随笔  :: 联系 :: 管理

扩展程序提供程序

Posted on 2006-10-09 15:02  Cracker  阅读(125)  评论(0)    收藏  举报

“扩展程序提供程序”是一种为其他组件提供属性的组件。
扩展程序提供程序提供的属性实际驻留在扩展程序提供程序对象本身,因此并不是它修改的组件的真正属性。在设计时,该属性将出现在任何附加到正在修改的组件的 PropertyGrid 中。不过,在运行时,您无法通过组件自身来访问属性。

using System;
using System.Collections;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Drawing;
using System.Windows.Forms;
using System.Windows.Forms.Design;

namespace MyComponentPro
{
    [ProvideProperty("Tesk", typeof(Control))]                   //指定提供的属性名和提供的类型
    public partial class TipControl : Component, IExtenderProvider
    {
        Hashtable hashtable = new Hashtable();             //Hashtable集合(键值对)用于存放每个组件的属性值

        public TipControl()
        {
            InitializeComponent();
        }

        public TipControl(IContainer container)
        {
            container.Add(this);

            InitializeComponent();
        }

        bool IExtenderProvider.CanExtend(object target)              //实现IExtenderProvider 接口的CanExtend()方法
        {                                                                 //每当用户选中组件时总是调用此方法,  是否提供属性
            if (target is Control && !(target is TipControl)
                 && !(target is Form))
            {
                return true;
            }
            return false;
        }

        public string GetTesk(Control control)                        //实现属性GetPropertyName()
        {
            string str = (string)hashtable[control];
            if (str == null)
            {
                return string.Empty;
            }
            return str;
        }

        public void SetTesk(Control control, string value)          ////实现属性SetPropertyName()
        {
            if (control == null)
            {
                value = string.Empty;
            }

            if (value.Length == 0)
            {
                hashtable.Remove(control);
            }
            else
            {
                hashtable[control] = value;
            }

        }
    }
}