擴充性提供者物件

「擴充性提供者」(Extender Provider) 是可提供屬性給其他元件的元件。 例如,在表單上加入 ToolTip 元件時,它就會將名為 ToolTip 的屬性提供給該表單上的每一個控制項。 然後 ToolTip 屬性就會顯示在每個控制項的 [屬性] 視窗中,並允許開發人員在設計階段設定這個屬性的值。

擴充性提供者所提供的屬性 (Property) 實際位於擴充性提供者物件本身,因此並不是所修改元件的真正屬性 (Property)。 在設計階段,這個屬性會顯示正在修改的元件之 [屬性] 視窗中。 但在執行階段就無法透過元件本身存取這個屬性 (Property)。 在下列程式碼範例中,表單是以名為 MyButton 的按鈕,及名為 MyToolTip 的 ToolTip 控制項建立,此控制項會提供 ToolTip 屬性。

' This is an example of code that is NOT CORRECT!
Dim myString as String
myString = MyButton.ToolTip
// This is an example of code that is NOT CORRECT!
string myString;
myString = MyButton.ToolTip;

以上語法將會產生編譯錯誤,因為編譯器 (Compiler) 無法將 ToolTip 識別為 MyButton 的屬性,原因是這個屬性實際上是由 MyToolTip 提供的。 以下範例將說明如何正確存取這個屬性 (Property):

Dim myString as String
myString = MyToolTip.GetToolTip(MyButton)
string myString;
myString = MyToolTip.GetToolTip(MyButton);

擴充性提供者是一種類別,因此本身也可以有屬性 (Property) 和方法。 若要將屬性 (Property) 指定為要提供給其他元件的屬性 (Property),可在類別層級套用 ProvidePropertyAttribute 屬性 (Attribute)。 這個屬性 (Attribute) 會指定要提供屬性的名稱以及被提供屬性的物件型別。 依照慣例,提供的屬性 (Property) 並不是以屬性 (Property) 實作,而是以一組方法實作。 這些方法必須將 "Get" 及 "Set" 加入至提供的屬性 (Property) 的名稱開頭。 以下範例將說明操作步驟。

Imports System.ComponentModel
<ProvideProperty("MyText", GetType(Control))> Public Class MyExtender
   <ExtenderProvidedProperty()> Public Function GetMyText(acontrol as _
      Control) as String
      ' Insert code to implement function.
   End Function
   Public Sub SetMytext (acontrol as Control)
      ' Insert code to implement function.
   End Function
End Class
using System.ComponentModel;
[ProvideProperty("MyText", typeof("Control"))]
public class MyExtender
{
[ExtenderProvidedProperty()]
   public string GetMyText(Control acontrol)
   {
      // Insert code to implement method.
   }
   public void SetMyText(Control acontrol)
   {
      // Insert code to implement method.
   }
}

實作所提供的屬性 (Property) 將需要 Hashtable 或其他類似的集合物件 (Collection Object),以記錄及擷取各控制項的屬性 (Property) 值。 如需詳細資訊,請參閱 HOW TO:實作擴充性提供者

每個擴充項 (Extender) 類別也都必須實作 IExtenderProvider 介面。 這個介面是由單一方法 CanExtend 組成,它會傳回 Boolean 值,並指示設計工具是否要擴充元件。 例如,您可能需要建立只將屬性 (Property) 提供給控制項的擴充項。 下列範例將示範如何實作 CanExtend 方法:

Imports System.ComponentModel
Public Function CanExtend(ByVal extendee As Object) As Boolean _
   Implements IExtenderProvider.CanExtend
   If Typeof extendee Is Control Then
      Return True
   Else
      Return False
   End If
End Function
public bool CanExtend(object extendee) 
{
   if (extendee is Control)
      return true;
   else
      return false;
}

請參閱

工作

HOW TO:實作擴充性提供者

HOW TO:實作 HelpLabel 擴充性提供者

參考

IExtenderProvider

ProvidePropertyAttribute

其他資源

擴充性提供者